From b345a781d75cc6c06f94d19a2ee0ae46296630c3 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 13 Jan 2017 12:41:27 -0800 Subject: [PATCH 001/282] Add test for class from external module is used in union --- .../reference/metadataOfClassFromAlias.js | 49 +++++++++++++++++++ .../metadataOfClassFromAlias.symbols | 28 +++++++++++ .../reference/metadataOfClassFromAlias.types | 31 ++++++++++++ .../compiler/metadataOfClassFromAlias.ts | 18 +++++++ 4 files changed, 126 insertions(+) create mode 100644 tests/baselines/reference/metadataOfClassFromAlias.js create mode 100644 tests/baselines/reference/metadataOfClassFromAlias.symbols create mode 100644 tests/baselines/reference/metadataOfClassFromAlias.types create mode 100644 tests/cases/compiler/metadataOfClassFromAlias.ts diff --git a/tests/baselines/reference/metadataOfClassFromAlias.js b/tests/baselines/reference/metadataOfClassFromAlias.js new file mode 100644 index 00000000000..9e229c2ca38 --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias.js @@ -0,0 +1,49 @@ +//// [tests/cases/compiler/metadataOfClassFromAlias.ts] //// + +//// [auxiliry.ts] + +export class SomeClass { + field: string; +} + +//// [test.ts] +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null; +} + +//// [auxiliry.js] +"use strict"; +var SomeClass = (function () { + function SomeClass() { + } + return SomeClass; +}()); +exports.SomeClass = SomeClass; +//// [test.js] +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +function annotation() { + return function (target) { }; +} +var ClassA = (function () { + function ClassA() { + } + return ClassA; +}()); +__decorate([ + annotation(), + __metadata("design:type", auxiliry_1.SomeClass) +], ClassA.prototype, "array", void 0); +exports.ClassA = ClassA; diff --git a/tests/baselines/reference/metadataOfClassFromAlias.symbols b/tests/baselines/reference/metadataOfClassFromAlias.symbols new file mode 100644 index 00000000000..2cf6ca18393 --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias.symbols @@ -0,0 +1,28 @@ +=== tests/cases/compiler/auxiliry.ts === + +export class SomeClass { +>SomeClass : Symbol(SomeClass, Decl(auxiliry.ts, 0, 0)) + + field: string; +>field : Symbol(SomeClass.field, Decl(auxiliry.ts, 1, 24)) +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) + +function annotation(): PropertyDecorator { +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>PropertyDecorator : Symbol(PropertyDecorator, Decl(lib.d.ts, --, --)) + + return (target: any): void => { }; +>target : Symbol(target, Decl(test.ts, 2, 12)) +} +export class ClassA { +>ClassA : Symbol(ClassA, Decl(test.ts, 3, 1)) + + @annotation() array: SomeClass | null; +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>array : Symbol(ClassA.array, Decl(test.ts, 4, 21)) +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) +} diff --git a/tests/baselines/reference/metadataOfClassFromAlias.types b/tests/baselines/reference/metadataOfClassFromAlias.types new file mode 100644 index 00000000000..1381ab7afac --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias.types @@ -0,0 +1,31 @@ +=== tests/cases/compiler/auxiliry.ts === + +export class SomeClass { +>SomeClass : SomeClass + + field: string; +>field : string +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : typeof SomeClass + +function annotation(): PropertyDecorator { +>annotation : () => PropertyDecorator +>PropertyDecorator : PropertyDecorator + + return (target: any): void => { }; +>(target: any): void => { } : (target: any) => void +>target : any +} +export class ClassA { +>ClassA : ClassA + + @annotation() array: SomeClass | null; +>annotation() : PropertyDecorator +>annotation : () => PropertyDecorator +>array : SomeClass +>SomeClass : SomeClass +>null : null +} diff --git a/tests/cases/compiler/metadataOfClassFromAlias.ts b/tests/cases/compiler/metadataOfClassFromAlias.ts new file mode 100644 index 00000000000..c7407c8d766 --- /dev/null +++ b/tests/cases/compiler/metadataOfClassFromAlias.ts @@ -0,0 +1,18 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @target: es5 +// @module: commonjs + +// @filename: auxiliry.ts +export class SomeClass { + field: string; +} + +//@filename: test.ts +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null; +} \ No newline at end of file From 839dde3cf293aab280c9680ef60f54bd0cd8525f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 17 Jan 2017 11:20:50 -0800 Subject: [PATCH 002/282] Mark as referenced aliases in Union that will get emitted as part of decorator metadaa Fixes #13449 --- src/compiler/checker.ts | 74 +++++++++++++++++-- src/compiler/transformers/ts.ts | 2 + .../reference/metadataOfClassFromAlias.js | 1 + .../reference/metadataOfClassFromAlias2.js | 49 ++++++++++++ .../metadataOfClassFromAlias2.symbols | 28 +++++++ .../reference/metadataOfClassFromAlias2.types | 31 ++++++++ .../compiler/metadataOfClassFromAlias2.ts | 18 +++++ 7 files changed, 197 insertions(+), 6 deletions(-) create mode 100644 tests/baselines/reference/metadataOfClassFromAlias2.js create mode 100644 tests/baselines/reference/metadataOfClassFromAlias2.symbols create mode 100644 tests/baselines/reference/metadataOfClassFromAlias2.types create mode 100644 tests/cases/compiler/metadataOfClassFromAlias2.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b4f8fdfeab5..eed762a9036 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16732,7 +16732,10 @@ namespace ts { * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node: TypeNode) { - const typeName = node && getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && getEntityNameFromTypeNode(node)); + } + + function markEntityNameOrEntityExpressionAsReference(typeName: EntityNameOrEntityNameExpression) { const rootName = typeName && getFirstIdentifier(typeName); const rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === SyntaxKind.Identifier ? SymbolFlags.Type : SymbolFlags.Namespace) | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -16743,6 +16746,65 @@ namespace ts { } } + function markDecoratorMedataDataTypeNodeAsReferenced(node: TypeNode): void { + const entityNameOrToken = getEntityNameForDecoratoryMetadata(node); + if (entityNameOrToken && isEntityName(entityNameOrToken)) { + markEntityNameOrEntityExpressionAsReference(entityNameOrToken); + } + } + + type voidUndefinedNullOrNeverTypeNode = Token; + + function getEntityNameForDecoratoryMetadata(node: TypeNode): EntityName | voidUndefinedNullOrNeverTypeNode { + if (node) { + switch (node.kind) { + case SyntaxKind.IntersectionType: + case SyntaxKind.UnionType: + let commonEntityName: EntityName | voidUndefinedNullOrNeverTypeNode; + for (const typeNode of (node).types) { + const individualEntityName = getEntityNameForDecoratoryMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + + const isCommonEntityName = commonEntityName && isEntityName(commonEntityName); + const isIndividualEntityName = isEntityName(individualEntityName); + if (isCommonEntityName && isIndividualEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!isIdentifier(commonEntityName) || + !isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else if (!isCommonEntityName) { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + + case SyntaxKind.ParenthesizedType: + return getEntityNameForDecoratoryMetadata((node).type); + + case SyntaxKind.TypeReference: + return (node).typeName; + + case SyntaxKind.VoidKeyword: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.NeverKeyword: + return node; + + } + } + } + function getParameterTypeNodeForDecoratorCheck(node: ParameterDeclaration): TypeNode { return node.dotDotDotToken ? getRestParameterElementType(node.type) : node.type; } @@ -16778,7 +16840,7 @@ namespace ts { const constructor = getFirstConstructorWithBody(node); if (constructor) { for (const parameter of constructor.parameters) { - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -16787,17 +16849,17 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: for (const parameter of (node).parameters) { - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced((node).type); + markDecoratorMedataDataTypeNodeAsReferenced((node).type); break; case SyntaxKind.PropertyDeclaration: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case SyntaxKind.Parameter: - markTypeNodeAsReferenced((node).type); + markDecoratorMedataDataTypeNodeAsReferenced((node).type); break; } } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index e2b8b8fe2ec..a27b9921a4e 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1739,6 +1739,8 @@ namespace ts { } function serializeUnionOrIntersectionType(node: UnionOrIntersectionTypeNode): SerializedTypeNode { + // Note when updating logic here also update getEntityNameForDecoratoryMetadata + // so that aliases can be marked as referenced let serializedUnion: SerializedTypeNode; for (const typeNode of node.types) { const serializedIndividual = serializeTypeNode(typeNode); diff --git a/tests/baselines/reference/metadataOfClassFromAlias.js b/tests/baselines/reference/metadataOfClassFromAlias.js index 9e229c2ca38..bf3d8bf860f 100644 --- a/tests/baselines/reference/metadataOfClassFromAlias.js +++ b/tests/baselines/reference/metadataOfClassFromAlias.js @@ -34,6 +34,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; +var auxiliry_1 = require("./auxiliry"); function annotation() { return function (target) { }; } diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.js b/tests/baselines/reference/metadataOfClassFromAlias2.js new file mode 100644 index 00000000000..70488af2b7e --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias2.js @@ -0,0 +1,49 @@ +//// [tests/cases/compiler/metadataOfClassFromAlias2.ts] //// + +//// [auxiliry.ts] + +export class SomeClass { + field: string; +} + +//// [test.ts] +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null | string; +} + +//// [auxiliry.js] +"use strict"; +var SomeClass = (function () { + function SomeClass() { + } + return SomeClass; +}()); +exports.SomeClass = SomeClass; +//// [test.js] +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +function annotation() { + return function (target) { }; +} +var ClassA = (function () { + function ClassA() { + } + return ClassA; +}()); +__decorate([ + annotation(), + __metadata("design:type", Object) +], ClassA.prototype, "array", void 0); +exports.ClassA = ClassA; diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.symbols b/tests/baselines/reference/metadataOfClassFromAlias2.symbols new file mode 100644 index 00000000000..ab183452f20 --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias2.symbols @@ -0,0 +1,28 @@ +=== tests/cases/compiler/auxiliry.ts === + +export class SomeClass { +>SomeClass : Symbol(SomeClass, Decl(auxiliry.ts, 0, 0)) + + field: string; +>field : Symbol(SomeClass.field, Decl(auxiliry.ts, 1, 24)) +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) + +function annotation(): PropertyDecorator { +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>PropertyDecorator : Symbol(PropertyDecorator, Decl(lib.d.ts, --, --)) + + return (target: any): void => { }; +>target : Symbol(target, Decl(test.ts, 2, 12)) +} +export class ClassA { +>ClassA : Symbol(ClassA, Decl(test.ts, 3, 1)) + + @annotation() array: SomeClass | null | string; +>annotation : Symbol(annotation, Decl(test.ts, 0, 39)) +>array : Symbol(ClassA.array, Decl(test.ts, 4, 21)) +>SomeClass : Symbol(SomeClass, Decl(test.ts, 0, 8)) +} diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.types b/tests/baselines/reference/metadataOfClassFromAlias2.types new file mode 100644 index 00000000000..75807845d1a --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromAlias2.types @@ -0,0 +1,31 @@ +=== tests/cases/compiler/auxiliry.ts === + +export class SomeClass { +>SomeClass : SomeClass + + field: string; +>field : string +} + +=== tests/cases/compiler/test.ts === +import { SomeClass } from './auxiliry'; +>SomeClass : typeof SomeClass + +function annotation(): PropertyDecorator { +>annotation : () => PropertyDecorator +>PropertyDecorator : PropertyDecorator + + return (target: any): void => { }; +>(target: any): void => { } : (target: any) => void +>target : any +} +export class ClassA { +>ClassA : ClassA + + @annotation() array: SomeClass | null | string; +>annotation() : PropertyDecorator +>annotation : () => PropertyDecorator +>array : string | SomeClass +>SomeClass : SomeClass +>null : null +} diff --git a/tests/cases/compiler/metadataOfClassFromAlias2.ts b/tests/cases/compiler/metadataOfClassFromAlias2.ts new file mode 100644 index 00000000000..05c44d9c677 --- /dev/null +++ b/tests/cases/compiler/metadataOfClassFromAlias2.ts @@ -0,0 +1,18 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @target: es5 +// @module: commonjs + +// @filename: auxiliry.ts +export class SomeClass { + field: string; +} + +//@filename: test.ts +import { SomeClass } from './auxiliry'; +function annotation(): PropertyDecorator { + return (target: any): void => { }; +} +export class ClassA { + @annotation() array: SomeClass | null | string; +} \ No newline at end of file From 3e142f8e524233b9cd6aa84f17ed0f4d3d719fdb Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 6 Feb 2017 08:47:11 -0800 Subject: [PATCH 003/282] Object literal freshness errors with spreads Previously, object literals with spreads in them would not issue object literal freshness errors. Fixes #13878 --- src/compiler/checker.ts | 2 ++ .../objectLiteralFreshnessWithSpread.errors.txt | 11 +++++++++++ .../objectLiteralFreshnessWithSpread.js | 16 ++++++++++++++++ .../compiler/objectLiteralFreshnessWithSpread.ts | 2 ++ 4 files changed, 31 insertions(+) create mode 100644 tests/baselines/reference/objectLiteralFreshnessWithSpread.errors.txt create mode 100644 tests/baselines/reference/objectLiteralFreshnessWithSpread.js create mode 100644 tests/cases/compiler/objectLiteralFreshnessWithSpread.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b5306771dd7..80a2f2f6e77 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11864,6 +11864,8 @@ namespace ts { if (spread.flags & TypeFlags.Object) { // only set the symbol and flags if this is a (fresh) object type spread.flags |= propagatedFlags; + spread.flags |= TypeFlags.FreshLiteral; + (spread as ObjectType).objectFlags |= ObjectFlags.ObjectLiteral; spread.symbol = node.symbol; } return spread; diff --git a/tests/baselines/reference/objectLiteralFreshnessWithSpread.errors.txt b/tests/baselines/reference/objectLiteralFreshnessWithSpread.errors.txt new file mode 100644 index 00000000000..ac6b56f6cea --- /dev/null +++ b/tests/baselines/reference/objectLiteralFreshnessWithSpread.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/objectLiteralFreshnessWithSpread.ts(2,35): error TS2322: Type '{ z: number; b: number; extra: number; a: number; }' is not assignable to type '{ a: any; b: any; }'. + Object literal may only specify known properties, and 'z' does not exist in type '{ a: any; b: any; }'. + + +==== tests/cases/compiler/objectLiteralFreshnessWithSpread.ts (1 errors) ==== + let x = { b: 1, extra: 2 } + let xx: { a, b } = { a: 1, ...x, z: 3 } // error for 'z', no error for 'extra' + ~~~~ +!!! error TS2322: Type '{ z: number; b: number; extra: number; a: number; }' is not assignable to type '{ a: any; b: any; }'. +!!! error TS2322: Object literal may only specify known properties, and 'z' does not exist in type '{ a: any; b: any; }'. + \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralFreshnessWithSpread.js b/tests/baselines/reference/objectLiteralFreshnessWithSpread.js new file mode 100644 index 00000000000..0a4222603a2 --- /dev/null +++ b/tests/baselines/reference/objectLiteralFreshnessWithSpread.js @@ -0,0 +1,16 @@ +//// [objectLiteralFreshnessWithSpread.ts] +let x = { b: 1, extra: 2 } +let xx: { a, b } = { a: 1, ...x, z: 3 } // error for 'z', no error for 'extra' + + +//// [objectLiteralFreshnessWithSpread.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var x = { b: 1, extra: 2 }; +var xx = __assign({ a: 1 }, x, { z: 3 }); // error for 'z', no error for 'extra' diff --git a/tests/cases/compiler/objectLiteralFreshnessWithSpread.ts b/tests/cases/compiler/objectLiteralFreshnessWithSpread.ts new file mode 100644 index 00000000000..7e8044e064a --- /dev/null +++ b/tests/cases/compiler/objectLiteralFreshnessWithSpread.ts @@ -0,0 +1,2 @@ +let x = { b: 1, extra: 2 } +let xx: { a, b } = { a: 1, ...x, z: 3 } // error for 'z', no error for 'extra' From 7e2517975c0dd86b7549f3ab4e231d9c207d0e65 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 30 Mar 2017 14:14:15 -0700 Subject: [PATCH 004/282] Basic functionality * pass context as argument in xToNode methods * make sourcefile optional in printer * start consolidating NodeBuilderFlags and TypeFormatFlags --- src/compiler/checker.ts | 186 +++++++++++++++++------------- src/compiler/emitter.ts | 24 ++-- src/compiler/factory.ts | 25 ++++ src/compiler/types.ts | 11 +- src/compiler/utilities.ts | 14 ++- src/services/codefixes/helpers.ts | 2 +- src/services/textChanges.ts | 24 +--- 7 files changed, 162 insertions(+), 124 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4e55a1c46b5..28ba350f38b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2188,8 +2188,7 @@ namespace ts { return result; } - - function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { + function oldTypeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { const writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); let result = writer.string(); @@ -2202,25 +2201,43 @@ namespace ts { return result; } - function createNodeBuilder() { - let context: NodeBuilderContext; + function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { + const str = oldTypeToString(type, enclosingDeclaration, flags); str; + const str2 = oldTypeToString(type, enclosingDeclaration, flags); str2; + const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, NodeBuilderFlags.ignoreErrors); + Debug.assert(typeNode !== undefined, "should always get typenode?"); + const newLine = NewLineKind.None; + const options = { newLine, removeComments: true }; + const writer = createTextWriter(""); + // writer.writeLine = noop; + const printer = createPrinter(options, writer); + printer.writeNode(EmitHint.Unspecified, typeNode, /*sourceFile*/ undefined, writer); + const result = writer.getText(); + const maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; + if (maxLength && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + + function createNodeBuilder() { return { typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { - context = createNodeBuilderContext(enclosingDeclaration, flags); - const resultingNode = typeToTypeNodeHelper(type); + const context = createNodeBuilderContext(enclosingDeclaration, flags); + const resultingNode = typeToTypeNodeHelper(type, context); const result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: (indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { - context = createNodeBuilderContext(enclosingDeclaration, flags); - const resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + const context = createNodeBuilderContext(enclosingDeclaration, flags); + const resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); const result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: (signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { - context = createNodeBuilderContext(enclosingDeclaration, flags); - const resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + const context = createNodeBuilderContext(enclosingDeclaration, flags); + const resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); const result = context.encounteredError ? undefined : resultingNode; return result; } @@ -2246,7 +2263,7 @@ namespace ts { }; } - function typeToTypeNodeHelper(type: Type): TypeNode { + function typeToTypeNodeHelper(type: Type, context: NodeBuilderContext): TypeNode { if (!type) { context.encounteredError = true; // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? @@ -2266,7 +2283,7 @@ namespace ts { return createKeywordTypeNode(SyntaxKind.BooleanKeyword); } if (type.flags & TypeFlags.Enum) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (TypeFlags.StringLiteral)) { @@ -2279,8 +2296,11 @@ namespace ts { return (type).intrinsicName === "true" ? createTrue() : createFalse(); } if (type.flags & TypeFlags.EnumLiteral) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return createTypeReferenceNode(name, /*typeArguments*/ undefined); + const parentSymbol = getParentOfSymbol(type.symbol); + const parentName = symbolToName(parentSymbol, /*expectsIdentifier*/ false, context); + const name = getNameOfSymbol(type.symbol, context); + const enumLiteralName = createQualifiedName(parentName, name); + return createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & TypeFlags.Void) { return createKeywordTypeNode(SyntaxKind.VoidKeyword); @@ -2317,18 +2337,18 @@ namespace ts { } if (objectFlags & ObjectFlags.ClassOrInterface) { Debug.assert(!!(type.flags & TypeFlags.Object)); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); // TODO(aozgaa): handle type arguments. return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & TypeFlags.TypeParameter) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (context.checkAlias && type.aliasSymbol) { - const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); + const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, context); const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); return createTypeReferenceNode(name, typeArgumentNodes); } @@ -2360,12 +2380,12 @@ namespace ts { if (type.flags & TypeFlags.Index) { const indexedType = (type).type; - const indexTypeNode = typeToTypeNodeHelper(indexedType); + const indexTypeNode = typeToTypeNodeHelper(indexedType, context); return createTypeOperatorNode(indexTypeNode); } if (type.flags & TypeFlags.IndexedAccess) { - const objectTypeNode = typeToTypeNodeHelper((type).objectType); - const indexTypeNode = typeToTypeNodeHelper((type).indexType); + const objectTypeNode = typeToTypeNodeHelper((type).objectType, context); + const indexTypeNode = typeToTypeNodeHelper((type).indexType, context); return createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } @@ -2374,7 +2394,7 @@ namespace ts { function mapToTypeNodeArray(types: Type[]): TypeNode[] { const result = []; for (const type of types) { - const typeNode = typeToTypeNodeHelper(type); + const typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); } @@ -2385,10 +2405,10 @@ namespace ts { function createMappedTypeNodeFromType(type: MappedType) { Debug.assert(!!(type.flags & TypeFlags.Object)); const typeParameter = getTypeParameterFromMappedType(type); - const typeParameterNode = typeParameterToDeclaration(typeParameter); + const typeParameterNode = typeParameterToDeclaration(typeParameter, context); const templateType = getTemplateTypeFromMappedType(type); - const templateTypeNode = typeToTypeNodeHelper(templateType); + const templateTypeNode = typeToTypeNodeHelper(templateType, context); const readonlyToken = type.declaration && type.declaration.readonlyToken ? createToken(SyntaxKind.ReadonlyKeyword) : undefined; const questionToken = type.declaration && type.declaration.questionToken ? createToken(SyntaxKind.QuestionToken) : undefined; @@ -2409,7 +2429,7 @@ namespace ts { const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - const entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + const entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false, context); return createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -2462,11 +2482,11 @@ namespace ts { if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType); + return signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { const signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType); + return signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context); } } @@ -2478,14 +2498,14 @@ namespace ts { } function createTypeQueryNodeFromSymbol(symbol: Symbol) { - const entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + const entityName = symbolToName(symbol, /*expectsIdentifier*/ false, context); return createTypeQueryNode(entityName); } function typeReferenceToTypeNode(type: TypeReference) { const typeArguments: Type[] = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - const elementType = typeToTypeNodeHelper(typeArguments[0]); + const elementType = typeToTypeNodeHelper(typeArguments[0], context); return createArrayTypeNode(elementType); } else if (type.target.objectFlags & ObjectFlags.Tuple) { @@ -2516,7 +2536,7 @@ namespace ts { // 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 (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { - const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); + const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true, context); if (!qualifiedName) { qualifiedName = createQualifiedName(qualifiedNamePart, /*right*/ undefined); } @@ -2529,7 +2549,7 @@ namespace ts { } } let entityName: EntityName = undefined; - const nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + const nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true, context); if (qualifiedName) { Debug.assert(!qualifiedName.right); qualifiedName.right = nameIdentifier; @@ -2547,16 +2567,16 @@ namespace ts { function createTypeNodesFromResolvedType(resolvedType: ResolvedType): TypeElement[] { const typeElements: TypeElement[] = []; for (const signature of resolvedType.callSignatures) { - typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature, context)); } for (const signature of resolvedType.constructSignatures) { - typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, IndexKind.String)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, IndexKind.String, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, IndexKind.Number)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, IndexKind.Number, context)); } const properties = resolvedType.properties; @@ -2570,12 +2590,12 @@ namespace ts { if (!oldDeclaration) { return; } - const propertyName = oldDeclaration.name; + const propertyName = getDeepSynthesizedClone(oldDeclaration.name); const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? createToken(SyntaxKind.QuestionToken) : undefined; if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length) { const signatures = getSignaturesOfType(propertyType, SignatureKind.Call); for (const signature of signatures) { - const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature); + const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); @@ -2584,7 +2604,7 @@ namespace ts { else { // TODO(aozgaa): should we create a node with explicit or implict any? - const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : createKeywordTypeNode(SyntaxKind.AnyKeyword); + const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : createKeywordTypeNode(SyntaxKind.AnyKeyword); typeElements.push(createPropertySignature( propertyName, optionalToken, @@ -2596,7 +2616,7 @@ namespace ts { } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind): IndexSignatureDeclaration { + function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword); const name = getNameFromIndexInfo(indexInfo); @@ -2608,7 +2628,7 @@ namespace ts { /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - const typeNode = typeToTypeNodeHelper(indexInfo.type); + const typeNode = typeToTypeNodeHelper(indexInfo.type, context); return createIndexSignatureDeclaration( /*decorators*/ undefined, indexInfo.isReadonly ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined, @@ -2616,55 +2636,62 @@ namespace ts { typeNode); } - function signatureToSignatureDeclarationHelper(signature: Signature, kind: SyntaxKind): SignatureDeclaration { + function signatureToSignatureDeclarationHelper(signature: Signature, kind: SyntaxKind, context: NodeBuilderContext): SignatureDeclaration { - const typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter)); - const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter)); - let returnTypeNode: TypeNode | TypePredicate; + const typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter, context)); + const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter, context)); + let returnTypeNode: TypeNode; if (signature.typePredicate) { const typePredicate = signature.typePredicate; const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? createIdentifier((typePredicate).parameterName) : createThisTypeNode(); - const typeNode = typeToTypeNodeHelper(typePredicate.type); + const typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = createTypePredicateNode(parameterName, typeNode); } else { const returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - const returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== SyntaxKind.AnyKeyword ? returnTypeNode : undefined; - - return createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if(context.flags & NodeBuilderFlags.suppressAnyReturnType) { + if(returnTypeNode && returnTypeNode.kind === SyntaxKind.AnyKeyword) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + return createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type: TypeParameter): TypeParameterDeclaration { + function typeParameterToDeclaration(type: TypeParameter, context: NodeBuilderContext): TypeParameterDeclaration { const constraint = getConstraintFromTypeParameter(type); - const constraintNode = constraint && typeToTypeNodeHelper(constraint); + const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); const defaultParameter = getDefaultFromTypeParameter(type); - const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ true, context); return createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol: Symbol): ParameterDeclaration { + function symbolToParameterDeclaration(parameterSymbol: Symbol, context: NodeBuilderContext): ParameterDeclaration { const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); const parameterType = getTypeOfSymbol(parameterSymbol); - const parameterTypeNode = typeToTypeNodeHelper(parameterType); + const parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + const name = getDeepSynthesizedClone(parameterDeclaration.name); // TODO(aozgaa): In the future, check initializer accessibility. const parameterNode = createParameter( parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && createToken(SyntaxKind.DotDotDotToken), // Clone name to remove trivia. - getSynthesizedClone(parameterDeclaration.name), + name, parameterDeclaration.questionToken && createToken(SyntaxKind.QuestionToken), parameterTypeNode, parameterDeclaration.initializer); return parameterNode; } - function symbolToName(symbol: Symbol, expectsIdentifier: true): Identifier; - function symbolToName(symbol: Symbol, expectsIdentifier: false): EntityName; - function symbolToName(symbol: Symbol, expectsIdentifier: boolean): EntityName { + function symbolToName(symbol: Symbol, expectsIdentifier: true, context: NodeBuilderContext): Identifier; + function symbolToName(symbol: Symbol, expectsIdentifier: false, context: NodeBuilderContext): EntityName; + function symbolToName(symbol: Symbol, expectsIdentifier: boolean, context: NodeBuilderContext): EntityName { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; @@ -2714,7 +2741,7 @@ namespace ts { } } - const symbolName = getNameOfSymbol(symbol); + const symbolName = getNameOfSymbol(symbol, context); const symbolNameWithTypeParameters = typeParameterString.length > 0 ? `${symbolName}<${typeParameterString}>` : symbolName; const identifier = createIdentifier(symbolNameWithTypeParameters); @@ -2754,29 +2781,28 @@ namespace ts { return [symbol]; } } - - function getNameOfSymbol(symbol: Symbol): string { - const declaration = firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { - return declarationNameToString((declaration.parent).name); - } - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case SyntaxKind.ClassExpression: - return "(Anonymous class)"; - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol: Symbol, context: NodeBuilderContext): string { + const declaration = firstOrUndefined(symbol.declarations); + if (declaration) { + if (declaration.name) { + return declarationNameToString(declaration.name); + } + if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { + return declarationNameToString((declaration.parent).name); + } + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case SyntaxKind.ClassExpression: + return "(Anonymous class)"; + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 616be35270e..f72d2bb19c1 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -213,7 +213,7 @@ namespace ts { emitLeadingCommentsOfPosition, } = comments; - let currentSourceFile: SourceFile; + let currentSourceFile: SourceFile | undefined; let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes. let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables. let generatedNames: Map; // Set of names generated by the NameGenerator. @@ -235,7 +235,7 @@ namespace ts { writeBundle }; - function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string { + function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined): string { switch (hint) { case EmitHint.SourceFile: Debug.assert(isSourceFile(node), "Expected a SourceFile node."); @@ -265,7 +265,7 @@ namespace ts { return endPrint(); } - function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter) { + function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, output: EmitTextWriter) { const previousWriter = writer; setWriter(output); print(hint, node, sourceFile); @@ -302,8 +302,10 @@ namespace ts { return text; } - function print(hint: EmitHint, node: Node, sourceFile: SourceFile) { - setSourceFile(sourceFile); + function print(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined) { + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } @@ -1101,7 +1103,7 @@ namespace ts { function emitPropertyAccessExpression(node: PropertyAccessExpression) { let indentBeforeDot = false; let indentAfterDot = false; - if (!(getEmitFlags(node) & EmitFlags.NoIndentation)) { + if (currentSourceFile && !(getEmitFlags(node) & EmitFlags.NoIndentation)) { const dotRangeStart = node.expression.end; const dotRangeEnd = skipTrivia(currentSourceFile.text, node.expression.end) + 1; const dotToken = { kind: SyntaxKind.DotToken, pos: dotRangeStart, end: dotRangeEnd }; @@ -2461,7 +2463,7 @@ namespace ts { const firstChild = children[0]; if (firstChild === undefined) { - return !rangeIsOnSingleLine(parentNode, currentSourceFile); + return !(currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile)); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(firstChild)) { return synthesizedNodeStartsOnNewLine(firstChild, format); @@ -2487,7 +2489,7 @@ namespace ts { return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); } else { - return !rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + return !(currentSourceFile && rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile)); } } else { @@ -2506,13 +2508,13 @@ namespace ts { const lastChild = lastOrUndefined(children); if (lastChild === undefined) { - return !rangeIsOnSingleLine(parentNode, currentSourceFile); + return !(currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile)); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(lastChild)) { return synthesizedNodeStartsOnNewLine(lastChild, format); } else { - return !rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + return !(currentSourceFile && rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile)); } } else { @@ -2901,7 +2903,7 @@ namespace ts { // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings, HeritageClauses = SingleLine | SpaceBetweenSiblings, - TypeLiteralMembers = MultiLine | Indented, + TypeLiteralMembers = SpaceBetweenBraces | SpaceBetweenSiblings | Indented, // MultiLine | Indented, TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 66b3eb713e5..4bf4d1a9519 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2,6 +2,26 @@ /// namespace ts { + export const nullTransformationContext: TransformationContext = { + enableEmitNotification: noop, + enableSubstitution: noop, + endLexicalEnvironment: () => undefined, + getCompilerOptions: notImplemented, + getEmitHost: notImplemented, + getEmitResolver: notImplemented, + hoistFunctionDeclaration: noop, + hoistVariableDeclaration: noop, + isEmitNotificationEnabled: notImplemented, + isSubstitutionEnabled: notImplemented, + onEmitNode: noop, + onSubstituteNode: notImplemented, + readEmitHelpers: notImplemented, + requestEmitHelper: noop, + resumeLexicalEnvironment: noop, + startLexicalEnvironment: noop, + suspendLexicalEnvironment: noop + }; + function createSynthesizedNode(kind: SyntaxKind): Node { const node = createNode(kind, -1, -1); node.flags |= NodeFlags.Synthesized; @@ -64,6 +84,11 @@ namespace ts { return clone; } + export function getDeepSynthesizedClone(node: T | undefined): T { + const clone = visitEachChild(node, getDeepSynthesizedClone, nullTransformationContext, /*nodeVisitor*/ undefined, getSynthesizedClone); + return nodeIsSynthesized(clone) ? clone : getSynthesizedClone(clone); + } + // Literals export function createLiteral(value: string): StringLiteral; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 038f8bf3166..12b9d333e3d 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2541,8 +2541,10 @@ namespace ts { allowQualifedNameInPlaceOfIdentifier = 1 << 1, allowTypeParameterInQualifiedName = 1 << 2, allowAnonymousIdentifier = 1 << 3, - allowEmptyUnionOrIntersection = 1 << 4, - allowEmptyTuple = 1 << 5 + allowEmptyUnionOrIntersection = 1 << 4, + allowEmptyTuple = 1 << 5, + suppressAnyReturnType = 1 << 6, + ignoreErrors = allowThisInObjectLiteral | allowQualifedNameInPlaceOfIdentifier | allowTypeParameterInQualifiedName | allowAnonymousIdentifier | allowEmptyUnionOrIntersection | allowEmptyTuple } export interface SymbolDisplayBuilder { @@ -3470,6 +3472,7 @@ namespace ts { export const enum NewLineKind { CarriageReturnLineFeed = 0, LineFeed = 1, + None = 2 } export interface LineAndCharacter { @@ -4115,7 +4118,7 @@ namespace ts { * the identifiers of the source file are used when generating unique names to avoid * collisions. */ - printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + printNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -4124,7 +4127,7 @@ namespace ts { * Prints a bundle of source files as-is, without any emit transformations. */ printBundle(bundle: Bundle): string; - /*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, writer: EmitTextWriter): void; + /*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; /*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter): void; /*@internal*/ writeBundle(bundle: Bundle, writer: EmitTextWriter): void; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 33cb0d8f489..9e39e66b646 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3272,13 +3272,15 @@ namespace ts { const carriageReturnLineFeed = "\r\n"; const lineFeed = "\n"; export function getNewLineCharacter(options: CompilerOptions | PrinterOptions): string { - if (options.newLine === NewLineKind.CarriageReturnLineFeed) { - return carriageReturnLineFeed; + switch (options.newLine) { + case NewLineKind.None: + return ""; + case NewLineKind.CarriageReturnLineFeed: + return carriageReturnLineFeed; + case NewLineKind.LineFeed: + return lineFeed; } - else if (options.newLine === NewLineKind.LineFeed) { - return lineFeed; - } - else if (sys) { + if (sys) { return sys.newLine; } return carriageReturnLineFeed; diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index b836815fc27..631fb560cd7 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -130,7 +130,7 @@ namespace ts.codefix { } function signatureToMethodDeclaration(signature: Signature, enclosingDeclaration: Node, body?: Block) { - const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration); + const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.suppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index afc98927495..63e3a95bf18 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -497,8 +497,8 @@ namespace ts.textChanges { readonly node: Node; } - export function getNonformattedText(node: Node, sourceFile: SourceFile, newLine: NewLineKind): NonFormattedText { - const options = { newLine, target: sourceFile.languageVersion }; + export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLine: NewLineKind): NonFormattedText { + const options = { newLine, target: sourceFile && sourceFile.languageVersion }; const writer = new Writer(getNewLineCharacter(options)); const printer = createPrinter(options, writer); printer.writeNode(EmitHint.Unspecified, node, sourceFile, writer); @@ -528,26 +528,6 @@ namespace ts.textChanges { return skipTrivia(s, 0) === s.length; } - const nullTransformationContext: TransformationContext = { - enableEmitNotification: noop, - enableSubstitution: noop, - endLexicalEnvironment: () => undefined, - getCompilerOptions: notImplemented, - getEmitHost: notImplemented, - getEmitResolver: notImplemented, - hoistFunctionDeclaration: noop, - hoistVariableDeclaration: noop, - isEmitNotificationEnabled: notImplemented, - isSubstitutionEnabled: notImplemented, - onEmitNode: noop, - onSubstituteNode: notImplemented, - readEmitHelpers: notImplemented, - requestEmitHelper: noop, - resumeLexicalEnvironment: noop, - startLexicalEnvironment: noop, - suspendLexicalEnvironment: noop - }; - function assignPositionsToNode(node: Node): Node { const visited = visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes From 4a3b38b2740665566be596705da873e1d257b879 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 5 Apr 2017 15:24:10 -0700 Subject: [PATCH 005/282] Refactor how we (internally) expose JS module resolution Also, provide a useful error if resolution fails. --- src/compiler/moduleNameResolver.ts | 21 +++++++++++++++++---- src/server/server.ts | 7 +++---- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 5280c794725..9e41d1dd667 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -2,7 +2,6 @@ /// namespace ts { - /* @internal */ export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; export function trace(host: ModuleResolutionHost): void { @@ -15,6 +14,7 @@ namespace ts { } /** Array that is only intended to be pushed to, never read. */ + /* @internal */ export interface Push { push(value: T): void; } @@ -675,12 +675,25 @@ namespace ts { } export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - export function nodeModuleNameResolverWorker(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, jsOnly = false): ResolvedModuleWithFailedLookupLocations { - const containingDirectory = getDirectoryPath(containingFile); + export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { + const { resolvedModule, failedLookupLocations } = + nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + if (!resolvedModule) { + throw new Error(`Could not resolve JS module ${moduleName} starting at ${initialDir}. Looked in: ${failedLookupLocations.join(", ")}`); + } + return resolvedModule.resolvedFileName; + } + + function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; diff --git a/src/server/server.ts b/src/server/server.ts index ab746f44f5b..d5ad3c9be05 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -702,12 +702,11 @@ namespace ts.server { } sys.require = (initialDir: string, moduleName: string): RequireResult => { - const result = nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, undefined, /*jsOnly*/ true); try { - return { module: require(result.resolvedModule.resolvedFileName), error: undefined }; + return { module: require(resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; } - catch (e) { - return { module: undefined, error: e }; + catch (error) { + return { module: undefined, error }; } }; From 92bea77ad3c570ac8bfcb6635cee429968b5a979 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 11 Apr 2017 13:57:21 -0700 Subject: [PATCH 006/282] Tsconfig inheritance: Do not resolve included files in an inherited tsconfig --- src/compiler/commandLineParser.ts | 186 ++++++++++++++++++------------ 1 file changed, 110 insertions(+), 76 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index a9df1d0d0b8..0709ed4a4aa 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1088,53 +1088,36 @@ namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ - export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: JsFileExtensionInfo[] = []): ParsedCommandLine { + export function parseJsonConfigFileContent( + json: any, + host: ParseConfigHost, + basePath: string, + existingOptions: CompilerOptions = {}, + configFileName?: string, + resolutionStack: Path[] = [], + extraFileExtensions: JsFileExtensionInfo[] = [], + ): ParsedCommandLine { const errors: Diagnostic[] = []; - basePath = normalizeSlashes(basePath); - const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))], - wildcardDirectories: {} - }; - } - let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + let options = (() => { + const { include, exclude, files, options } = parseConfig(json, host, basePath, configFileName, resolutionStack, errors); + if (include) json.include = include; + if (exclude) json.exclude = exclude; + if (files) json.files = files; + return options; + })(); + + options = extend(existingOptions, options); + options.configFilePath = configFileName; + // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. const jsonOptions = json["typeAcquisition"] || json["typingOptions"]; const typeAcquisition: TypeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - if (json["extends"]) { - let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}]; - if (typeof json["extends"] === "string") { - [include, exclude, files, baseOptions] = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]); - } - else { - errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = assign({}, baseOptions, options); - } - - options = extend(existingOptions, options); - options.configFilePath = configFileName; - - const { fileNames, wildcardDirectories } = getFileNames(errors); + const { fileNames, wildcardDirectories } = getFileNames(); const compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { @@ -1147,40 +1130,7 @@ namespace ts { compileOnSave }; - function tryExtendsName(extendedConfig: string): [string[], string[], string[], CompilerOptions] { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(isRootedDiskPath(extendedConfig) || startsWith(normalizeSlashes(extendedConfig), "./") || startsWith(normalizeSlashes(extendedConfig), "../"))) { - errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - let extendedConfigPath = toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = `${extendedConfigPath}.json` as Path; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - const extendedResult = readConfigFile(extendedConfigPath, path => host.readFile(path)); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - const extendedDirname = getDirectoryPath(extendedConfigPath); - const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path); - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - const result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/undefined, getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push(...result.errors); - const [include, exclude, files] = map(["include", "exclude", "files"], key => { - if (!json[key] && extendedResult.config[key]) { - return map(extendedResult.config[key], updatePath); - } - }); - return [include, exclude, files, result.options]; - } - - function getFileNames(errors: Diagnostic[]): ExpandResult { + function getFileNames(): ExpandResult { let fileNames: string[]; if (hasProperty(json, "files")) { if (isArray(json["files"])) { @@ -1213,9 +1163,6 @@ namespace ts { errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (hasProperty(json, "excludes")) { - errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -1245,6 +1192,93 @@ namespace ts { } } + type ParsedTsconfig = { include?: string[], exclude?: string[], files?: string[], options: CompilerOptions }; + + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig( + json: any, + host: ParseConfigHost, + basePath: string, + configFileName: string, + resolutionStack: Path[] = [], + errors: Diagnostic[], + ): ParsedTsconfig { + + basePath = normalizeSlashes(basePath); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName); + + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))); + return { options: {} }; + } + + if (hasProperty(json, "excludes")) { + errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + + let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + let include: string[] | undefined = json.include, exclude: string[] | undefined = json.exclude, files: string[] | undefined = json.files; + + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + const base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + options = assign({}, base.options, options); + } + } + + return { include, exclude, files, options }; + } + + function getExtendedConfig( + extended: any, // Usually a string. + host: ts.ParseConfigHost, + basePath: string, + getCanonicalFileName: (fileName: string) => string, + resolutionStack: Path[], + errors: Diagnostic[], + ): ParsedTsconfig | undefined { + if (typeof extended !== "string") { + errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(isRootedDiskPath(extended) || startsWith(normalizeSlashes(extended), "./") || startsWith(normalizeSlashes(extended), "../"))) { + errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + + let extendedConfigPath = toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json" as Path; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + + const extendedResult = readConfigFile(extendedConfigPath, path => host.readFile(path)); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + + const extendedDirname = getDirectoryPath(extendedConfigPath); + const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path); + const { include, exclude, files, options } = parseConfig(extendedResult.config, host, extendedDirname, getBaseFileName(extendedConfigPath), resolutionStack, errors); + return { include: map(include, updatePath), exclude: map(exclude, updatePath), files: map(files, updatePath), options }; + } + export function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean { if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) { return false; From 8c559a4f083af397af98f18efc9980d295ffd4ca Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 12 Apr 2017 15:11:16 -0700 Subject: [PATCH 007/282] Respond to PR comments --- src/compiler/commandLineParser.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 0709ed4a4aa..587529a5beb 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1103,9 +1103,9 @@ namespace ts { let options = (() => { const { include, exclude, files, options } = parseConfig(json, host, basePath, configFileName, resolutionStack, errors); - if (include) json.include = include; - if (exclude) json.exclude = exclude; - if (files) json.files = files; + if (include) { json.include = include; } + if (exclude) { json.exclude = exclude; } + if (files) { json.files = files; } return options; })(); @@ -1203,7 +1203,7 @@ namespace ts { host: ParseConfigHost, basePath: string, configFileName: string, - resolutionStack: Path[] = [], + resolutionStack: Path[], errors: Diagnostic[], ): ParsedTsconfig { @@ -1251,8 +1251,10 @@ namespace ts { return undefined; } + extended = normalizeSlashes(extended); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(isRootedDiskPath(extended) || startsWith(normalizeSlashes(extended), "./") || startsWith(normalizeSlashes(extended), "../"))) { + if (!(isRootedDiskPath(extended) || startsWith(extended, "./") || startsWith(extended, "../"))) { errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); return undefined; } From 0eaa8eb3ab9ad1db8cf95c51d8e02c9d65ee40cf Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 14 Apr 2017 11:08:05 -0700 Subject: [PATCH 008/282] Updating PR as per feedback. OneType|null is again treated as object instead of simplifying it --- src/compiler/checker.ts | 40 +++++++++---------- src/compiler/transformers/ts.ts | 12 ++---- src/compiler/utilities.ts | 4 -- .../reference/metadataOfClassFromAlias.js | 6 +-- .../metadataOfClassFromAlias.symbols | 3 +- .../reference/metadataOfClassFromAlias.types | 1 - .../reference/metadataOfClassFromAlias2.js | 3 +- .../metadataOfClassFromAlias2.symbols | 3 +- .../reference/metadataOfClassFromAlias2.types | 1 - .../reference/metadataOfUnionWithNull.js | 16 ++++---- 10 files changed, 36 insertions(+), 53 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f118fdbba1e..c0d3cd17fdb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -18625,33 +18625,36 @@ namespace ts { } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ function markDecoratorMedataDataTypeNodeAsReferenced(node: TypeNode): void { - const entityNameOrToken = getEntityNameForDecoratoryMetadata(node); - if (entityNameOrToken && isEntityName(entityNameOrToken)) { - markEntityNameOrEntityExpressionAsReference(entityNameOrToken); + const entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); } } - type voidUndefinedNullOrNeverTypeNode = Token; - - function getEntityNameForDecoratoryMetadata(node: TypeNode): EntityName | voidUndefinedNullOrNeverTypeNode { + function getEntityNameForDecoratorMetadata(node: TypeNode): EntityName { if (node) { switch (node.kind) { case SyntaxKind.IntersectionType: case SyntaxKind.UnionType: - let commonEntityName: EntityName | voidUndefinedNullOrNeverTypeNode; + let commonEntityName: EntityName; for (const typeNode of (node).types) { - const individualEntityName = getEntityNameForDecoratoryMetadata(typeNode); + const individualEntityName = getEntityNameForDecoratorMetadata(typeNode); if (!individualEntityName) { - // Individual is something like string number - // So it would be serialized to either that type or object + // Individual is something like string number + // So it would be serialized to either that type or object // Safe to return here return undefined; } - const isCommonEntityName = commonEntityName && isEntityName(commonEntityName); - const isIndividualEntityName = isEntityName(individualEntityName); - if (isCommonEntityName && isIndividualEntityName) { + if (commonEntityName) { // Note this is in sync with the transformation that happens for type node. // Keep this in sync with serializeUnionOrIntersectionType // Verify if they refer to same entity and is identifier @@ -18662,24 +18665,17 @@ namespace ts { return undefined; } } - else if (!isCommonEntityName) { + else { commonEntityName = individualEntityName; } } return commonEntityName; case SyntaxKind.ParenthesizedType: - return getEntityNameForDecoratoryMetadata((node).type); + return getEntityNameForDecoratorMetadata((node).type); case SyntaxKind.TypeReference: return (node).typeName; - - case SyntaxKind.VoidKeyword: - case SyntaxKind.UndefinedKeyword: - case SyntaxKind.NullKeyword: - case SyntaxKind.NeverKeyword: - return node; - } } } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 06bd3fef032..68bba667058 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1761,25 +1761,19 @@ namespace ts { } function serializeUnionOrIntersectionType(node: UnionOrIntersectionTypeNode): SerializedTypeNode { - // Note when updating logic here also update getEntityNameForDecoratoryMetadata + // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced let serializedUnion: SerializedTypeNode; for (const typeNode of node.types) { const serializedIndividual = serializeTypeNode(typeNode); - if (isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } // If there exists union that is not void 0 expression, check if the the common type is identifier. // anything more complex and we will just default to Object - else if (serializedUnion && !isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!isIdentifier(serializedUnion) || !isIdentifier(serializedIndividual) || diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 3b4b87c956f..c6328324bbb 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3566,10 +3566,6 @@ namespace ts { return node.kind === SyntaxKind.Identifier; } - export function isVoidExpression(node: Node): node is VoidExpression { - return node.kind === SyntaxKind.VoidExpression; - } - export function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > GeneratedIdentifierKind.None; diff --git a/tests/baselines/reference/metadataOfClassFromAlias.js b/tests/baselines/reference/metadataOfClassFromAlias.js index bf3d8bf860f..c99f7cc2e23 100644 --- a/tests/baselines/reference/metadataOfClassFromAlias.js +++ b/tests/baselines/reference/metadataOfClassFromAlias.js @@ -1,7 +1,6 @@ //// [tests/cases/compiler/metadataOfClassFromAlias.ts] //// //// [auxiliry.ts] - export class SomeClass { field: string; } @@ -17,6 +16,7 @@ export class ClassA { //// [auxiliry.js] "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var SomeClass = (function () { function SomeClass() { } @@ -34,7 +34,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; -var auxiliry_1 = require("./auxiliry"); +Object.defineProperty(exports, "__esModule", { value: true }); function annotation() { return function (target) { }; } @@ -45,6 +45,6 @@ var ClassA = (function () { }()); __decorate([ annotation(), - __metadata("design:type", auxiliry_1.SomeClass) + __metadata("design:type", Object) ], ClassA.prototype, "array", void 0); exports.ClassA = ClassA; diff --git a/tests/baselines/reference/metadataOfClassFromAlias.symbols b/tests/baselines/reference/metadataOfClassFromAlias.symbols index 2cf6ca18393..b4d20403275 100644 --- a/tests/baselines/reference/metadataOfClassFromAlias.symbols +++ b/tests/baselines/reference/metadataOfClassFromAlias.symbols @@ -1,10 +1,9 @@ === tests/cases/compiler/auxiliry.ts === - export class SomeClass { >SomeClass : Symbol(SomeClass, Decl(auxiliry.ts, 0, 0)) field: string; ->field : Symbol(SomeClass.field, Decl(auxiliry.ts, 1, 24)) +>field : Symbol(SomeClass.field, Decl(auxiliry.ts, 0, 24)) } === tests/cases/compiler/test.ts === diff --git a/tests/baselines/reference/metadataOfClassFromAlias.types b/tests/baselines/reference/metadataOfClassFromAlias.types index 1381ab7afac..a14f72ee619 100644 --- a/tests/baselines/reference/metadataOfClassFromAlias.types +++ b/tests/baselines/reference/metadataOfClassFromAlias.types @@ -1,5 +1,4 @@ === tests/cases/compiler/auxiliry.ts === - export class SomeClass { >SomeClass : SomeClass diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.js b/tests/baselines/reference/metadataOfClassFromAlias2.js index 70488af2b7e..bcdbb34ac50 100644 --- a/tests/baselines/reference/metadataOfClassFromAlias2.js +++ b/tests/baselines/reference/metadataOfClassFromAlias2.js @@ -1,7 +1,6 @@ //// [tests/cases/compiler/metadataOfClassFromAlias2.ts] //// //// [auxiliry.ts] - export class SomeClass { field: string; } @@ -17,6 +16,7 @@ export class ClassA { //// [auxiliry.js] "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var SomeClass = (function () { function SomeClass() { } @@ -34,6 +34,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; +Object.defineProperty(exports, "__esModule", { value: true }); function annotation() { return function (target) { }; } diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.symbols b/tests/baselines/reference/metadataOfClassFromAlias2.symbols index ab183452f20..a20296c76af 100644 --- a/tests/baselines/reference/metadataOfClassFromAlias2.symbols +++ b/tests/baselines/reference/metadataOfClassFromAlias2.symbols @@ -1,10 +1,9 @@ === tests/cases/compiler/auxiliry.ts === - export class SomeClass { >SomeClass : Symbol(SomeClass, Decl(auxiliry.ts, 0, 0)) field: string; ->field : Symbol(SomeClass.field, Decl(auxiliry.ts, 1, 24)) +>field : Symbol(SomeClass.field, Decl(auxiliry.ts, 0, 24)) } === tests/cases/compiler/test.ts === diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.types b/tests/baselines/reference/metadataOfClassFromAlias2.types index 75807845d1a..20979a5c77d 100644 --- a/tests/baselines/reference/metadataOfClassFromAlias2.types +++ b/tests/baselines/reference/metadataOfClassFromAlias2.types @@ -1,5 +1,4 @@ === tests/cases/compiler/auxiliry.ts === - export class SomeClass { >SomeClass : SomeClass diff --git a/tests/baselines/reference/metadataOfUnionWithNull.js b/tests/baselines/reference/metadataOfUnionWithNull.js index cc594ae326d..0c834be9687 100644 --- a/tests/baselines/reference/metadataOfUnionWithNull.js +++ b/tests/baselines/reference/metadataOfUnionWithNull.js @@ -65,15 +65,15 @@ var B = (function () { }()); __decorate([ PropDeco, - __metadata("design:type", String) + __metadata("design:type", Object) ], B.prototype, "x"); __decorate([ PropDeco, - __metadata("design:type", Boolean) + __metadata("design:type", Object) ], B.prototype, "y"); __decorate([ PropDeco, - __metadata("design:type", String) + __metadata("design:type", Object) ], B.prototype, "z"); __decorate([ PropDeco, @@ -89,11 +89,11 @@ __decorate([ ], B.prototype, "c"); __decorate([ PropDeco, - __metadata("design:type", void 0) + __metadata("design:type", Object) ], B.prototype, "d"); __decorate([ PropDeco, - __metadata("design:type", typeof Symbol === "function" ? Symbol : Object) + __metadata("design:type", Object) ], B.prototype, "e"); __decorate([ PropDeco, @@ -101,13 +101,13 @@ __decorate([ ], B.prototype, "f"); __decorate([ PropDeco, - __metadata("design:type", A) + __metadata("design:type", Object) ], B.prototype, "g"); __decorate([ PropDeco, - __metadata("design:type", B) + __metadata("design:type", Object) ], B.prototype, "h"); __decorate([ PropDeco, - __metadata("design:type", typeof Symbol === "function" ? Symbol : Object) + __metadata("design:type", Object) ], B.prototype, "j"); From 55388d16b4c9de3686465c857eeb3d6db33f1492 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 19 Apr 2017 10:36:40 -0700 Subject: [PATCH 009/282] Readonly type literal members --- src/compiler/checker.ts | 9 ++++++--- src/compiler/factory.ts | 10 ++++++---- src/compiler/visitor.ts | 2 ++ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 28ba350f38b..0fd09251024 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2602,14 +2602,17 @@ namespace ts { } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : createKeywordTypeNode(SyntaxKind.AnyKeyword); - typeElements.push(createPropertySignature( + + const modifiers = isReadonlySymbol(propertySymbol) ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined; + const propertySignature = createPropertySignature( + modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/undefined)); + /*initializer*/undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 4bf4d1a9519..6b265c03d25 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -480,8 +480,9 @@ namespace ts { // Signature elements - export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature { + export function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature { const propertySignature = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature; + propertySignature.modifiers = asNodeArray(modifiers); propertySignature.name = asName(name); propertySignature.questionToken = questionToken; propertySignature.type = type; @@ -489,12 +490,13 @@ namespace ts { return propertySignature; } - export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { - return node.name !== name + export function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { + return node.modifiers !== modifiers + || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) : node; } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 297d2cc0dde..523d4cb8e32 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -355,6 +355,8 @@ namespace ts { case SyntaxKind.PropertySignature: return updatePropertySignature((node), + // TODO: tokenVisitor or visitor for a nodearray of tokens? + nodesVisitor((node).modifiers, visitor, isToken), visitNode((node).name, visitor, isPropertyName), visitNode((node).questionToken, tokenVisitor, isToken), visitNode((node).type, visitor, isTypeNode), From 10afa2f6420202507bb4eb453878bfa5886046dc Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 19 Apr 2017 11:11:19 -0700 Subject: [PATCH 010/282] No space in empty type litereal --- src/compiler/emitter.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index f283bc0217a..afafee51bf7 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -954,7 +954,9 @@ namespace ts { function emitTypeLiteral(node: TypeLiteralNode) { write("{"); - emitList(node, node.members, ListFormat.TypeLiteralMembers); + if (node.members.length > 0) { + emitList(node, node.members, ListFormat.SingleLineTypeLiteralMembers); + } write("}"); } @@ -2945,7 +2947,8 @@ namespace ts { // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings, HeritageClauses = SingleLine | SpaceBetweenSiblings, - TypeLiteralMembers = SpaceBetweenBraces | SpaceBetweenSiblings | Indented, // MultiLine | Indented, + SingleLineTypeLiteralMembers = SpaceBetweenBraces | SpaceBetweenSiblings | Indented, // MultiLine | Indented, + MultiLineTypeLiteralMembers = MultiLine | Indented, TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, From d0f371659004673b7c767ec0511143f69682e36c Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 19 Apr 2017 11:11:26 -0700 Subject: [PATCH 011/282] typo --- src/compiler/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4d8e886b2ce..53507e3aa38 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2572,7 +2572,7 @@ namespace ts { export interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; From 8a1456ff7585ed87dc00e023d6168993dd36ee45 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 25 Apr 2017 14:55:31 -0700 Subject: [PATCH 012/282] Clean up computeEnumMemberValues function --- src/compiler/checker.ts | 281 ++++++++++++++++------------------------ 1 file changed, 112 insertions(+), 169 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 18e57303c12..a3e65b4eb65 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -20669,107 +20669,86 @@ namespace ts { function computeEnumMemberValues(node: EnumDeclaration) { const nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & NodeCheckFlags.EnumValuesComputed)) { - const enumSymbol = getSymbolOfNode(node); - const enumType = getDeclaredTypeOfSymbol(enumSymbol); - let autoValue = 0; // set to undefined when enum member is non-constant - const ambient = isInAmbientContext(node); - const enumIsConst = isConst(node); - - for (const member of node.members) { - if (isComputedNonLiteralName(member.name)) { - error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - const text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - - const previousEnumMemberIsNonConstant = autoValue === undefined; - - const initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, Diagnostics.Enum_member_must_have_initializer); - } - - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } - } - nodeLinks.flags |= NodeCheckFlags.EnumValuesComputed; - } - - function computeConstantValueForEnumMemberInitializer(initializer: Expression, enumType: Type, enumIsConst: boolean, ambient: boolean): number { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - let reportError = true; - const value = evalConstant(initializer); - - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + let autoValue = 0; + for (const member of node.members) { + const value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } + } + } - return value; + function computeMemberValue(member: EnumMember, autoValue: number) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + const text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (isInAmbientContext(member.parent) && !isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, Diagnostics.Enum_member_must_have_initializer); + return undefined; + } - function evalConstant(e: Node): number { - switch (e.kind) { - case SyntaxKind.PrefixUnaryExpression: - const value = evalConstant((e).operand); - if (value === undefined) { - return undefined; - } - switch ((e).operator) { + function computeConstantValue(member: EnumMember): number { + const isConstEnum = isConst(member.parent); + const initializer = member.initializer; + const value = evaluate(member.initializer); + if (value !== undefined) { + if (isConstEnum && !isFinite(value)) { + error(initializer, isNaN(value) ? + Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (isConstEnum) { + error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (isInAmbientContext(member.parent)) { + error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + 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); + } + return value; + + function evaluate(expr: Expression): number { + switch (expr.kind) { + case SyntaxKind.PrefixUnaryExpression: + const value = evaluate((expr).operand); + if (typeof value === "number") { + switch ((expr).operator) { case SyntaxKind.PlusToken: return value; case SyntaxKind.MinusToken: return -value; case SyntaxKind.TildeToken: return ~value; } - return undefined; - case SyntaxKind.BinaryExpression: - const left = evalConstant((e).left); - if (left === undefined) { - return undefined; - } - const right = evalConstant((e).right); - if (right === undefined) { - return undefined; - } - switch ((e).operatorToken.kind) { + } + break; + case SyntaxKind.BinaryExpression: + const left = evaluate((expr).left); + const right = evaluate((expr).right); + if (typeof left === "number" && typeof right === "number") { + switch ((expr).operatorToken.kind) { case SyntaxKind.BarToken: return left | right; case SyntaxKind.AmpersandToken: return left & right; case SyntaxKind.GreaterThanGreaterThanToken: return left >> right; @@ -20782,90 +20761,54 @@ namespace ts { case SyntaxKind.MinusToken: return left - right; case SyntaxKind.PercentToken: return left % right; } - return undefined; - case SyntaxKind.NumericLiteral: - checkGrammarNumericLiteral(e); - return +(e).text; - case SyntaxKind.ParenthesizedExpression: - return evalConstant((e).expression); - case SyntaxKind.Identifier: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.PropertyAccessExpression: - const member = initializer.parent; - const currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - let enumType: Type; - let propertyName: string; - - if (e.kind === SyntaxKind.Identifier) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType = currentType; - propertyName = (e).text; + } + break; + case SyntaxKind.NumericLiteral: + checkGrammarNumericLiteral(expr); + return +(expr).text; + case SyntaxKind.ParenthesizedExpression: + return evaluate((expr).expression); + case SyntaxKind.Identifier: + return evaluateEnumMember(expr, getSymbolOfNode(member.parent), (expr).text); + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.PropertyAccessExpression: + if (isConstantMemberAccess(expr)) { + const type = getTypeOfExpression((expr).expression); + if (type.symbol && type.symbol.flags & SymbolFlags.Enum) { + const name = expr.kind === SyntaxKind.PropertyAccessExpression ? + (expr).name.text : + ((expr).argumentExpression).text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - let expression: Expression; - if (e.kind === SyntaxKind.ElementAccessExpression) { - if ((e).argumentExpression === undefined || - (e).argumentExpression.kind !== SyntaxKind.StringLiteral) { - return undefined; - } - expression = (e).expression; - propertyName = ((e).argumentExpression).text; - } - else { - expression = (e).expression; - propertyName = (e).name.text; - } + } + break; + } + return undefined; + } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - let current = expression; - while (current) { - if (current.kind === SyntaxKind.Identifier) { - break; - } - else if (current.kind === SyntaxKind.PropertyAccessExpression) { - current = (current).expression; - } - else { - return undefined; - } - } - - enumType = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType.symbol && (enumType.symbol.flags & SymbolFlags.Enum))) { - return undefined; - } - } - - if (propertyName === undefined) { - return undefined; - } - - const property = getPropertyOfObjectType(enumType, propertyName); - if (!property || !(property.flags & SymbolFlags.EnumMember)) { - return undefined; - } - - const propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - - return getNodeLinks(propertyDecl).enumMemberValue; + function evaluateEnumMember(expr: Expression, enumSymbol: Symbol, name: string) { + const memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + const declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return 0; } } + return undefined; } } + function isConstantMemberAccess(node: Expression): boolean { + return node.kind === SyntaxKind.Identifier || + node.kind === SyntaxKind.PropertyAccessExpression && isConstantMemberAccess((node).expression) || + node.kind === SyntaxKind.ElementAccessExpression && isConstantMemberAccess((node).expression) && + (node).argumentExpression.kind === SyntaxKind.StringLiteral; + } + function checkEnumDeclaration(node: EnumDeclaration) { if (!produceDiagnostics) { return; From f61efe5e19d35d81d5baa11d4539f92df5e50806 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 25 Apr 2017 14:55:51 -0700 Subject: [PATCH 013/282] Accept new baselines --- tests/baselines/reference/forwardRefInEnum.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/baselines/reference/forwardRefInEnum.js b/tests/baselines/reference/forwardRefInEnum.js index 555454dccaa..592adbd2534 100644 --- a/tests/baselines/reference/forwardRefInEnum.js +++ b/tests/baselines/reference/forwardRefInEnum.js @@ -19,11 +19,11 @@ var E1; (function (E1) { // illegal case // forward reference to the element of the same enum - E1[E1["X"] = E1.Y] = "X"; - E1[E1["X1"] = E1["Y"]] = "X1"; + E1[E1["X"] = 0] = "X"; + E1[E1["X1"] = 0] = "X1"; // forward reference to the element of the same enum - E1[E1["Y"] = E1.Z] = "Y"; - E1[E1["Y1"] = E1["Z"]] = "Y1"; + E1[E1["Y"] = 0] = "Y"; + E1[E1["Y1"] = 0] = "Y1"; })(E1 || (E1 = {})); (function (E1) { E1[E1["Z"] = 4] = "Z"; From 19a1c2ca612001d2fe956dce60f7f963441a346e Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 26 Apr 2017 14:18:11 -0700 Subject: [PATCH 014/282] Store actual literal value in LiteralType instances --- src/compiler/checker.ts | 64 ++++++++++++++++++------------------- src/compiler/types.ts | 10 +++++- src/services/completions.ts | 2 +- 3 files changed, 41 insertions(+), 35 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a3e65b4eb65..be72d9d657a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -309,8 +309,8 @@ namespace ts { let flowLoopCount = 0; let visitedFlowCount = 0; - const emptyStringType = getLiteralTypeForText(TypeFlags.StringLiteral, ""); - const zeroType = getLiteralTypeForText(TypeFlags.NumberLiteral, "0"); + const emptyStringType = getLiteralType(""); + const zeroType = getLiteralType(0); const resolutionTargets: TypeSystemEntity[] = []; const resolutionResults: boolean[] = []; @@ -1869,7 +1869,7 @@ namespace ts { } function createTypeofType() { - return getUnionType(convertToArray(typeofEQFacts.keys(), s => getLiteralTypeForText(TypeFlags.StringLiteral, s))); + return getUnionType(convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore @@ -2320,11 +2320,8 @@ namespace ts { const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); return createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (TypeFlags.StringLiteral)) { - return createLiteralTypeNode((createLiteral((type).text))); - } - if (type.flags & (TypeFlags.NumberLiteral)) { - return createLiteralTypeNode((createNumericLiteral((type).text))); + if (type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { + return createLiteralTypeNode(createLiteral((type).value)); } if (type.flags & TypeFlags.BooleanLiteral) { return (type).intrinsicName === "true" ? createTrue() : createFalse(); @@ -2891,7 +2888,7 @@ namespace ts { } function literalTypeToString(type: LiteralType) { - return type.flags & TypeFlags.StringLiteral ? `"${escapeString((type).text)}"` : (type).text; + return type.flags & TypeFlags.StringLiteral ? `"${escapeString((type).value)}"` : "" + (type).value; } function getNameOfSymbol(symbol: Symbol): string { @@ -4933,11 +4930,11 @@ namespace ts { return true; } - function createEnumLiteralType(symbol: Symbol, baseType: EnumType, text: string) { + function createEnumLiteralType(symbol: Symbol, baseType: EnumType, value: number) { const type = createType(TypeFlags.EnumLiteral); type.symbol = symbol; type.baseType = baseType; - type.text = text; + type.value = value; return type; } @@ -4956,7 +4953,7 @@ namespace ts { const memberSymbol = getSymbolOfNode(member); const value = getEnumMemberValue(member); if (!memberTypes[value]) { - const memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); + const memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, value); memberTypeList.push(memberType); } } @@ -5510,7 +5507,7 @@ namespace ts { // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & TypeFlags.StringLiteral) { - const propName = (t).text; + const propName = (t).value; const modifiersProp = getPropertyOfType(modifiersType, propName); const isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & SymbolFlags.Optional); const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName); @@ -7216,7 +7213,7 @@ namespace ts { function getLiteralTypeFromPropertyName(prop: Symbol) { return getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier || startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(TypeFlags.StringLiteral, unescapeIdentifier(prop.name)); + getLiteralType(unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type: Type) { @@ -7253,7 +7250,7 @@ namespace ts { function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode, cacheSymbol: boolean) { const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; const propName = indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral | TypeFlags.EnumLiteral) ? - (indexType).text : + "" + (indexType).value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? getPropertyNameForKnownSymbolName(((accessExpression.argumentExpression).name).text) : undefined; @@ -7301,7 +7298,7 @@ namespace ts { if (accessNode) { const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? (accessNode).argumentExpression : (accessNode).indexType; if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { - error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, (indexType).text, typeToString(objectType)); + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (indexType).value, typeToString(objectType)); } else if (indexType.flags & (TypeFlags.String | TypeFlags.Number)) { error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -7512,16 +7509,16 @@ namespace ts { return prop.flags & SymbolFlags.Method && find(prop.declarations, decl => isClassLike(decl.parent)); } - function createLiteralType(flags: TypeFlags, text: string) { + function createLiteralType(flags: TypeFlags, value: string | number) { const type = createType(flags); - type.text = text; + type.value = value; return type; } function getFreshTypeOfLiteralType(type: Type) { if (type.flags & TypeFlags.StringOrNumberLiteral && !(type.flags & TypeFlags.FreshLiteral)) { if (!(type).freshType) { - const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).text); + const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).value); freshType.regularType = type; (type).freshType = freshType; } @@ -7534,11 +7531,12 @@ namespace ts { return type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral ? (type).regularType : type; } - function getLiteralTypeForText(flags: TypeFlags, text: string) { - const map = flags & TypeFlags.StringLiteral ? stringLiteralTypes : numericLiteralTypes; + function getLiteralType(value: string | number) { + const map = typeof value === "number" ? numericLiteralTypes : stringLiteralTypes; + const text = "" + value; let type = map.get(text); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + map.set(text, type = createLiteralType(typeof value === "number" ? TypeFlags.NumberLiteral : TypeFlags.StringLiteral, value)); } return type; } @@ -8434,7 +8432,7 @@ namespace ts { if ((source.flags & TypeFlags.Number | source.flags & TypeFlags.NumberLiteral) && target.flags & TypeFlags.EnumLike) return true; if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.EnumLiteral && - (source).text === (target).text && + (source).value === (target).value && isEnumTypeRelatedTo((source).baseType, (target).baseType, errorReporter)) { return true; } @@ -9713,8 +9711,8 @@ namespace ts { // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type: Type): TypeFlags { return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type).types) : - type.flags & TypeFlags.StringLiteral ? (type).text === "" ? TypeFlags.StringLiteral : 0 : - type.flags & TypeFlags.NumberLiteral ? (type).text === "0" ? TypeFlags.NumberLiteral : 0 : + type.flags & TypeFlags.StringLiteral ? (type).value === "" ? TypeFlags.StringLiteral : 0 : + type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : type.flags & TypeFlags.BooleanLiteral ? type === falseType ? TypeFlags.BooleanLiteral : 0 : type.flags & TypeFlags.PossiblyFalsy; } @@ -10595,14 +10593,14 @@ namespace ts { } if (flags & TypeFlags.StringLiteral) { return strictNullChecks ? - (type).text === "" ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts : - (type).text === "" ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts; + (type).value === "" ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts : + (type).value === "" ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts; } if (flags & (TypeFlags.Number | TypeFlags.Enum)) { return strictNullChecks ? TypeFacts.NumberStrictFacts : TypeFacts.NumberFacts; } if (flags & (TypeFlags.NumberLiteral | TypeFlags.EnumLiteral)) { - const isZero = (type).text === "0"; + const isZero = (type).value === 0; return strictNullChecks ? isZero ? TypeFacts.ZeroStrictFacts : TypeFacts.NonZeroStrictFacts : isZero ? TypeFacts.ZeroFacts : TypeFacts.NonZeroFacts; @@ -13616,7 +13614,7 @@ namespace ts { // Hello World const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - const stringLiteralTypeName = (elementType).text; + const stringLiteralTypeName = (elementType).value; const intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -14861,7 +14859,7 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.NumericLiteral: case SyntaxKind.StringLiteral: - return getLiteralTypeForText(TypeFlags.StringLiteral, (element.name).text); + return getLiteralType((element.name).text); case SyntaxKind.ComputedPropertyName: const nameType = checkComputedPropertyName(element.name); @@ -16345,7 +16343,7 @@ namespace ts { return silentNeverType; } if (node.operator === SyntaxKind.MinusToken && node.operand.kind === SyntaxKind.NumericLiteral) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(TypeFlags.NumberLiteral, "" + -(node.operand).text)); + return getFreshTypeOfLiteralType(getLiteralType(-(node.operand).text)); } switch (node.operator) { case SyntaxKind.PlusToken: @@ -17021,9 +17019,9 @@ namespace ts { } switch (node.kind) { case SyntaxKind.StringLiteral: - return getFreshTypeOfLiteralType(getLiteralTypeForText(TypeFlags.StringLiteral, (node).text)); + return getFreshTypeOfLiteralType(getLiteralType((node).text)); case SyntaxKind.NumericLiteral: - return getFreshTypeOfLiteralType(getLiteralTypeForText(TypeFlags.NumberLiteral, (node).text)); + return getFreshTypeOfLiteralType(getLiteralType(+(node).text)); case SyntaxKind.TrueKeyword: return trueType; case SyntaxKind.FalseKeyword: diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 2389ba80753..c259366542b 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3036,11 +3036,19 @@ namespace ts { // String literal types (TypeFlags.StringLiteral) // Numeric literal types (TypeFlags.NumberLiteral) export interface LiteralType extends Type { - text: string; // Text of literal + value: string | number; // Value of literal freshType?: LiteralType; // Fresh version of type regularType?: LiteralType; // Regular version of type } + export interface StringLiteralType extends LiteralType { + value: string; + } + + export interface NumberLiteralType extends LiteralType { + value: number; + } + // Enum types (TypeFlags.Enum) export interface EnumType extends Type { memberTypes: EnumLiteralType[]; diff --git a/src/services/completions.ts b/src/services/completions.ts index 6ac3762b4c7..93f690c90f2 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -272,7 +272,7 @@ namespace ts.Completions { } else if (type.flags & TypeFlags.StringLiteral) { result.push({ - name: (type).text, + name: (type).value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.variableElement, sortText: "0" From a504022e7b1b935f3e216de7b709e3a06c4a8716 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 28 Apr 2017 09:11:04 -0700 Subject: [PATCH 015/282] Classify literal enum members and NumberLiteral/StringLiteral etc. --- src/compiler/checker.ts | 227 +++++++++++++++++++++------------------- src/compiler/types.ts | 14 +-- 2 files changed, 122 insertions(+), 119 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index be72d9d657a..4af13dfa21e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2316,7 +2316,7 @@ namespace ts { if (type.flags & TypeFlags.Boolean) { return createKeywordTypeNode(SyntaxKind.BooleanKeyword); } - if (type.flags & TypeFlags.Enum) { + if (type.flags & TypeFlags.EnumLike && !(type.flags & TypeFlags.Union)) { const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); return createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -2326,10 +2326,6 @@ namespace ts { if (type.flags & TypeFlags.BooleanLiteral) { return (type).intrinsicName === "true" ? createTrue() : createFalse(); } - if (type.flags & TypeFlags.EnumLiteral) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & TypeFlags.Void) { return createKeywordTypeNode(SyntaxKind.VoidKeyword); } @@ -2845,12 +2841,14 @@ namespace ts { flags |= t.flags; if (!(t.flags & TypeFlags.Nullable)) { if (t.flags & (TypeFlags.BooleanLiteral | TypeFlags.EnumLiteral)) { - const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : (t).baseType; - const count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & TypeFlags.Union) { + const count = (baseType).types.length; + if (i + count <= types.length && types[i + count - 1] === (baseType).types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -3048,7 +3046,7 @@ namespace ts { else if (getObjectFlags(type) & ObjectFlags.Reference) { writeTypeReference(type, nextFlags); } - else if (type.flags & TypeFlags.EnumLiteral) { + else if (type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union)) { buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); writePunctuation(writer, SyntaxKind.DotToken); appendSymbolNameOnly(type.symbol, writer); @@ -3424,7 +3422,7 @@ namespace ts { let type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, TypeFlags.Undefined); + type = getNullableType(type, TypeFlags.Undefined); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -4003,7 +4001,7 @@ namespace ts { } function addOptionality(type: Type, optional: boolean): Type { - return strictNullChecks && optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type; + return strictNullChecks && optional ? getNullableType(type, TypeFlags.Undefined) : type; } // Return the inferred type for a variable, parameter, or property declaration @@ -4422,7 +4420,7 @@ namespace ts { links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & SymbolFlags.Optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type; + links.type = strictNullChecks && symbol.flags & SymbolFlags.Optional ? getNullableType(type, TypeFlags.Undefined) : type; } } } @@ -4930,53 +4928,63 @@ namespace ts { return true; } - function createEnumLiteralType(symbol: Symbol, baseType: EnumType, value: number) { - const type = createType(TypeFlags.EnumLiteral); + function createEnumLiteralType(symbol: Symbol, value: number) { + const type = createLiteralType(TypeFlags.NumberLiteral | TypeFlags.EnumLiteral, value); type.symbol = symbol; - type.baseType = baseType; - type.value = value; return type; } + function getBaseTypeOfEnumLiteralType(type: Type) { + return type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - if (!links.declaredType) { - const enumType = links.declaredType = createType(TypeFlags.Enum); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - const memberTypeList: Type[] = []; - const memberTypes: EnumLiteralType[] = []; - for (const declaration of enumType.symbol.declarations) { - if (declaration.kind === SyntaxKind.EnumDeclaration) { - computeEnumMemberValues(declaration); - for (const member of (declaration).members) { - const memberSymbol = getSymbolOfNode(member); - const value = getEnumMemberValue(member); - if (!memberTypes[value]) { - const memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, value); - memberTypeList.push(memberType); - } + if (links.declaredType) { + return links.declaredType; + } + if (enumHasLiteralMembers(symbol)) { + const memberTypeList: Type[] = []; + const memberTypes: LiteralType[] = []; + for (const declaration of symbol.declarations) { + if (declaration.kind === SyntaxKind.EnumDeclaration) { + computeEnumMemberValues(declaration); + for (const member of (declaration).members) { + const memberSymbol = getSymbolOfNode(member); + const value = getEnumMemberValue(member); + if (!memberTypes[value]) { + const memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, value); + memberTypeList.push(memberType); } } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= TypeFlags.Union; - (enumType).types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length > 1) { + for (const declaration of symbol.declarations) { + if (declaration.kind === SyntaxKind.EnumDeclaration) { + for (const member of (declaration).members) { + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberTypes[getEnumMemberValue(member)]; + } + } } + const enumType = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + enumType.flags |= TypeFlags.EnumLiteral; + enumType.symbol = symbol; + return links.declaredType = enumType; } } - return links.declaredType; + const enumType = createType(TypeFlags.Enum); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.declaredType) { - const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & TypeFlags.Union ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -7249,7 +7257,7 @@ namespace ts { function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode, cacheSymbol: boolean) { const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; - const propName = indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral | TypeFlags.EnumLiteral) ? + const propName = indexType.flags & TypeFlags.StringOrNumberLiteral ? "" + (indexType).value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? getPropertyNameForKnownSymbolName(((accessExpression.argumentExpression).name).text) : @@ -8383,29 +8391,27 @@ namespace ts { false; } - function isEnumTypeRelatedTo(source: EnumType, target: EnumType, errorReporter?: ErrorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol: Symbol, targetSymbol: Symbol, errorReporter?: ErrorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - const id = source.id + "," + target.id; + const id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); const relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & SymbolFlags.RegularEnum) || !(target.symbol.flags & SymbolFlags.RegularEnum) || - (source.flags & TypeFlags.Union) !== (target.flags & TypeFlags.Union)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & SymbolFlags.RegularEnum) || !(targetSymbol.flags & SymbolFlags.RegularEnum)) { enumRelation.set(id, false); return false; } - const targetEnumType = getTypeOfSymbol(target.symbol); - for (const property of getPropertiesOfType(getTypeOfSymbol(source.symbol))) { + const targetEnumType = getTypeOfSymbol(targetSymbol); + for (const property of getPropertiesOfType(getTypeOfSymbol(sourceSymbol))) { if (property.flags & SymbolFlags.EnumMember) { const targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & SymbolFlags.EnumMember)) { if (errorReporter) { errorReporter(Diagnostics.Property_0_is_missing_in_type_1, property.name, - typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); + typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); } enumRelation.set(id, false); return false; @@ -8422,25 +8428,19 @@ namespace ts { if (source.flags & TypeFlags.StringLike && target.flags & TypeFlags.String) return true; if (source.flags & TypeFlags.NumberLike && target.flags & TypeFlags.Number) return true; if (source.flags & TypeFlags.BooleanLike && target.flags & TypeFlags.Boolean) return true; - if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.Enum && (source).baseType === target) return true; - if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum && isEnumTypeRelatedTo(source, target, errorReporter)) return true; + if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.EnumLiteral) { + if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (source.flags & TypeFlags.Literal && target.flags & TypeFlags.Literal && + (source).value === (target).value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; + } if (source.flags & TypeFlags.Undefined && (!strictNullChecks || target.flags & (TypeFlags.Undefined | TypeFlags.Void))) return true; if (source.flags & TypeFlags.Null && (!strictNullChecks || target.flags & TypeFlags.Null)) return true; if (source.flags & TypeFlags.Object && target.flags & TypeFlags.NonPrimitive) return true; if (relation === assignableRelation || relation === comparableRelation) { if (source.flags & TypeFlags.Any) return true; - if ((source.flags & TypeFlags.Number | source.flags & TypeFlags.NumberLiteral) && target.flags & TypeFlags.EnumLike) return true; - if (source.flags & TypeFlags.EnumLiteral && - target.flags & TypeFlags.EnumLiteral && - (source).value === (target).value && - isEnumTypeRelatedTo((source).baseType, (target).baseType, errorReporter)) { - return true; - } - if (source.flags & TypeFlags.EnumLiteral && - target.flags & TypeFlags.Enum && - isEnumTypeRelatedTo(target, (source).baseType, errorReporter)) { - return true; - } + if (source.flags & (TypeFlags.Number | TypeFlags.NumberLiteral) && !(source.flags & TypeFlags.EnumLiteral) && target.flags & TypeFlags.EnumLike) return true; } return false; } @@ -9603,7 +9603,7 @@ namespace ts { return getUnionType(types, /*subtypeReduction*/ true); } const supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & TypeFlags.Nullable); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & TypeFlags.Nullable); } function reportNoCommonSupertypeError(types: Type[], errorLocation: Node, errorMessageChainHead: DiagnosticMessageChain): void { @@ -9668,26 +9668,26 @@ namespace ts { function isLiteralType(type: Type): boolean { return type.flags & TypeFlags.Boolean ? true : - type.flags & TypeFlags.Union ? type.flags & TypeFlags.Enum ? true : !forEach((type).types, t => !isUnitType(t)) : - isUnitType(type); + type.flags & TypeFlags.Union ? type.flags & TypeFlags.EnumLiteral ? true : !forEach((type).types, t => !isUnitType(t)) : + isUnitType(type); } function getBaseTypeOfLiteralType(type: Type): Type { - return type.flags & TypeFlags.StringLiteral ? stringType : + return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : + type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : - type.flags & TypeFlags.BooleanLiteral ? booleanType : - type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : - type; + type.flags & TypeFlags.BooleanLiteral ? booleanType : + type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : + type; } function getWidenedLiteralType(type: Type): Type { - return type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : + return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : + type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : - type.flags & TypeFlags.BooleanLiteral ? booleanType : - type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : - type; + type.flags & TypeFlags.BooleanLiteral ? booleanType : + type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : + type; } /** @@ -9712,23 +9712,9 @@ namespace ts { function getFalsyFlags(type: Type): TypeFlags { return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type).types) : type.flags & TypeFlags.StringLiteral ? (type).value === "" ? TypeFlags.StringLiteral : 0 : - type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : - type.flags & TypeFlags.BooleanLiteral ? type === falseType ? TypeFlags.BooleanLiteral : 0 : - type.flags & TypeFlags.PossiblyFalsy; - } - - function includeFalsyTypes(type: Type, flags: TypeFlags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - const types = [type]; - if (flags & TypeFlags.StringLike) types.push(emptyStringType); - if (flags & TypeFlags.NumberLike) types.push(zeroType); - if (flags & TypeFlags.BooleanLike) types.push(falseType); - if (flags & TypeFlags.Void) types.push(voidType); - if (flags & TypeFlags.Undefined) types.push(undefinedType); - if (flags & TypeFlags.Null) types.push(nullType); - return getUnionType(types); + type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : + type.flags & TypeFlags.BooleanLiteral ? type === falseType ? TypeFlags.BooleanLiteral : 0 : + type.flags & TypeFlags.PossiblyFalsy; } function removeDefinitelyFalsyTypes(type: Type): Type { @@ -9737,6 +9723,28 @@ namespace ts { type; } + function extractDefinitelyFalsyTypes(type: Type): Type { + return mapType(type, getDefinitelyFalsyPartOfType); + } + + function getDefinitelyFalsyPartOfType(type: Type): Type { + return type.flags & TypeFlags.String ? emptyStringType : + type.flags & TypeFlags.Number ? zeroType : + type.flags & TypeFlags.Boolean || type === falseType ? falseType : + type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null) || + type.flags & TypeFlags.StringLiteral && (type).value === "" || + type.flags & TypeFlags.NumberLiteral && (type).value === 0 ? type : + neverType; + } + + function getNullableType(type: Type, flags: TypeFlags): Type { + const missing = (flags & ~type.flags) & (TypeFlags.Undefined | TypeFlags.Null); + return missing === 0 ? type : + missing === TypeFlags.Undefined ? getUnionType([type, undefinedType]) : + missing === TypeFlags.Null ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } + function getNonNullableType(type: Type): Type { return strictNullChecks ? getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull) : type; } @@ -10074,7 +10082,7 @@ namespace ts { } return; } - if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && !(source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum) || + if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && !(source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.EnumLiteral) || source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -10592,14 +10600,15 @@ namespace ts { return strictNullChecks ? TypeFacts.StringStrictFacts : TypeFacts.StringFacts; } if (flags & TypeFlags.StringLiteral) { + const isEmpty = (type).value === ""; return strictNullChecks ? - (type).value === "" ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts : - (type).value === "" ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts; + isEmpty ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts : + isEmpty ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts; } if (flags & (TypeFlags.Number | TypeFlags.Enum)) { return strictNullChecks ? TypeFacts.NumberStrictFacts : TypeFacts.NumberFacts; } - if (flags & (TypeFlags.NumberLiteral | TypeFlags.EnumLiteral)) { + if (flags & TypeFlags.NumberLiteral) { const isZero = (type).value === 0; return strictNullChecks ? isZero ? TypeFacts.ZeroStrictFacts : TypeFacts.NonZeroStrictFacts : @@ -10832,7 +10841,7 @@ namespace ts { } return true; } - if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.Enum && (source).baseType === target) { + if (source.flags & TypeFlags.EnumLiteral && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -11813,7 +11822,7 @@ namespace ts { isInAmbientContext(declaration); const initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, getRootDeclaration(declaration) as VariableLikeDeclaration) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, TypeFlags.Undefined); + getNullableType(type, TypeFlags.Undefined); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -15752,7 +15761,7 @@ namespace ts { if (strictNullChecks) { const declaration = symbol.valueDeclaration; if (declaration && (declaration).initializer) { - return includeFalsyTypes(type, TypeFlags.Undefined); + return getNullableType(type, TypeFlags.Undefined); } } return type; @@ -16851,7 +16860,7 @@ namespace ts { return checkInExpression(left, right, leftType, rightType); case SyntaxKind.AmpersandAmpersandToken: return getTypeFacts(leftType) & TypeFacts.Truthy ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case SyntaxKind.BarBarToken: return getTypeFacts(leftType) & TypeFacts.Falsy ? @@ -17940,7 +17949,7 @@ namespace ts { checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & TypeFlags.Enum && !(type).memberTypes && getNodeLinks(node).resolvedSymbol.flags & SymbolFlags.EnumMember) { + if (type.flags & TypeFlags.Enum && getNodeLinks(node).resolvedSymbol.flags & SymbolFlags.EnumMember) { error(node, Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -22567,7 +22576,7 @@ namespace ts { ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & TypeFormatFlags.AddUndefined) { - type = includeFalsyTypes(type, TypeFlags.Undefined); + type = getNullableType(type, TypeFlags.Undefined); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index c259366542b..f17dec4bd12 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2961,7 +2961,7 @@ namespace ts { StringLiteral = 1 << 5, NumberLiteral = 1 << 6, BooleanLiteral = 1 << 7, - EnumLiteral = 1 << 8, + EnumLiteral = 1 << 8, // Enum literal or union of enum literals ESSymbol = 1 << 9, // Type of symbol primitive introduced in ES6 Void = 1 << 10, Undefined = 1 << 11, @@ -2987,7 +2987,7 @@ namespace ts { /* @internal */ Nullable = Undefined | Null, - Literal = StringLiteral | NumberLiteral | BooleanLiteral | EnumLiteral, + Literal = StringLiteral | NumberLiteral | BooleanLiteral, StringOrNumberLiteral = StringLiteral | NumberLiteral, /* @internal */ DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null, @@ -2995,9 +2995,9 @@ namespace ts { /* @internal */ Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, /* @internal */ - Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal, + Primitive = String | Number | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal, StringLike = String | StringLiteral | Index, - NumberLike = Number | NumberLiteral | Enum | EnumLiteral, + NumberLike = Number | NumberLiteral | Enum, BooleanLike = Boolean | BooleanLiteral, EnumLike = Enum | EnumLiteral, UnionOrIntersection = Union | Intersection, @@ -3051,12 +3051,6 @@ namespace ts { // Enum types (TypeFlags.Enum) export interface EnumType extends Type { - memberTypes: EnumLiteralType[]; - } - - // Enum types (TypeFlags.EnumLiteral) - export interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; // Base enum type } export const enum ObjectFlags { From 50a37cea5764f82cb1b16f5c3d87e44cd55ab4f3 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 28 Apr 2017 09:11:20 -0700 Subject: [PATCH 016/282] Accept new baselines --- .../enumAssignmentCompat3.errors.txt | 20 ++++-- tests/baselines/reference/literalTypes2.types | 2 +- .../logicalAndOperatorWithEveryType.types | 2 +- .../logicalOrOperatorWithEveryType.types | 14 ++--- .../baselines/reference/metadataOfUnion.types | 2 +- .../reference/subtypesOfUnion.errors.txt | 60 +++++++++--------- ...IfEveryConstituentTypeIsSubtype.errors.txt | 61 +++++++++---------- 7 files changed, 83 insertions(+), 78 deletions(-) diff --git a/tests/baselines/reference/enumAssignmentCompat3.errors.txt b/tests/baselines/reference/enumAssignmentCompat3.errors.txt index 558540c32c8..a458733bcc2 100644 --- a/tests/baselines/reference/enumAssignmentCompat3.errors.txt +++ b/tests/baselines/reference/enumAssignmentCompat3.errors.txt @@ -1,15 +1,19 @@ -tests/cases/compiler/enumAssignmentCompat3.ts(68,1): error TS2324: Property 'd' is missing in type 'First.E'. +tests/cases/compiler/enumAssignmentCompat3.ts(68,1): error TS2322: Type 'Abcd.E' is not assignable to type 'First.E'. + Property 'd' is missing in type 'First.E'. tests/cases/compiler/enumAssignmentCompat3.ts(70,1): error TS2322: Type 'Cd.E' is not assignable to type 'First.E'. Property 'd' is missing in type 'First.E'. tests/cases/compiler/enumAssignmentCompat3.ts(71,1): error TS2322: Type 'Nope' is not assignable to type 'E'. tests/cases/compiler/enumAssignmentCompat3.ts(72,1): error TS2322: Type 'Decl.E' is not assignable to type 'First.E'. -tests/cases/compiler/enumAssignmentCompat3.ts(75,1): error TS2324: Property 'c' is missing in type 'Ab.E'. +tests/cases/compiler/enumAssignmentCompat3.ts(75,1): error TS2322: Type 'First.E' is not assignable to type 'Ab.E'. + Property 'c' is missing in type 'Ab.E'. tests/cases/compiler/enumAssignmentCompat3.ts(76,1): error TS2322: Type 'First.E' is not assignable to type 'Cd.E'. + Property 'a' is missing in type 'Cd.E'. tests/cases/compiler/enumAssignmentCompat3.ts(77,1): error TS2322: Type 'E' is not assignable to type 'Nope'. tests/cases/compiler/enumAssignmentCompat3.ts(78,1): error TS2322: Type 'First.E' is not assignable to type 'Decl.E'. tests/cases/compiler/enumAssignmentCompat3.ts(82,1): error TS2322: Type 'Const.E' is not assignable to type 'First.E'. tests/cases/compiler/enumAssignmentCompat3.ts(83,1): error TS2322: Type 'First.E' is not assignable to type 'Const.E'. -tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' is missing in type 'First.E'. +tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2322: Type 'Merged.E' is not assignable to type 'First.E'. + Property 'd' is missing in type 'First.E'. ==== tests/cases/compiler/enumAssignmentCompat3.ts (11 errors) ==== @@ -82,7 +86,8 @@ tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' abc = secondAbc; // ok abc = secondAbcd; // missing 'd' ~~~ -!!! error TS2324: Property 'd' is missing in type 'First.E'. +!!! error TS2322: Type 'Abcd.E' is not assignable to type 'First.E'. +!!! error TS2322: Property 'd' is missing in type 'First.E'. abc = secondAb; // ok abc = secondCd; // missing 'd' ~~~ @@ -98,10 +103,12 @@ tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' secondAbcd = abc; // ok secondAb = abc; // missing 'c' ~~~~~~~~ -!!! error TS2324: Property 'c' is missing in type 'Ab.E'. +!!! error TS2322: Type 'First.E' is not assignable to type 'Ab.E'. +!!! error TS2322: Property 'c' is missing in type 'Ab.E'. secondCd = abc; // missing 'a' and 'b' ~~~~~~~~ !!! error TS2322: Type 'First.E' is not assignable to type 'Cd.E'. +!!! error TS2322: Property 'a' is missing in type 'Cd.E'. nope = abc; // nope! ~~~~ !!! error TS2322: Type 'E' is not assignable to type 'Nope'. @@ -121,7 +128,8 @@ tests/cases/compiler/enumAssignmentCompat3.ts(86,1): error TS2324: Property 'd' // merged enums compare all their members abc = merged; // missing 'd' ~~~ -!!! error TS2324: Property 'd' is missing in type 'First.E'. +!!! error TS2322: Type 'Merged.E' is not assignable to type 'First.E'. +!!! error TS2322: Property 'd' is missing in type 'First.E'. merged = abc; // ok abc = merged2; // ok merged2 = abc; // ok \ No newline at end of file diff --git a/tests/baselines/reference/literalTypes2.types b/tests/baselines/reference/literalTypes2.types index 716b016f64e..ab1d3e199d2 100644 --- a/tests/baselines/reference/literalTypes2.types +++ b/tests/baselines/reference/literalTypes2.types @@ -290,7 +290,7 @@ function f3() { >c2 : 1 | "two" let x3 = c3; ->x3 : number | boolean | E +>x3 : number | boolean >c3 : true | E.A | 123 let x4 = c4; diff --git a/tests/baselines/reference/logicalAndOperatorWithEveryType.types b/tests/baselines/reference/logicalAndOperatorWithEveryType.types index 54770acfab4..cbe37d54a4f 100644 --- a/tests/baselines/reference/logicalAndOperatorWithEveryType.types +++ b/tests/baselines/reference/logicalAndOperatorWithEveryType.types @@ -365,7 +365,7 @@ var rf5 = a5 && a6; var rf6 = a6 && a6; >rf6 : E ->a6 && a6 : E.b | E.c +>a6 && a6 : E >a6 : E >a6 : E.b | E.c diff --git a/tests/baselines/reference/logicalOrOperatorWithEveryType.types b/tests/baselines/reference/logicalOrOperatorWithEveryType.types index 327ae64cf07..5e6fa98d749 100644 --- a/tests/baselines/reference/logicalOrOperatorWithEveryType.types +++ b/tests/baselines/reference/logicalOrOperatorWithEveryType.types @@ -128,7 +128,7 @@ var rb5 = a5 || a2; // void || boolean is void | boolean var rb6 = a6 || a2; // enum || boolean is E | boolean >rb6 : boolean | E ->a6 || a2 : boolean | E +>a6 || a2 : boolean | E.b | E.c >a6 : E >a2 : boolean @@ -248,7 +248,7 @@ var rd5 = a5 || a4; // void || string is void | string var rd6 = a6 || a4; // enum || string is enum | string >rd6 : string | E ->a6 || a4 : string | E +>a6 || a4 : string | E.b | E.c >a6 : E >a4 : string @@ -308,7 +308,7 @@ var re5 = a5 || a5; // void || void is void var re6 = a6 || a5; // enum || void is enum | void >re6 : void | E ->a6 || a5 : void | E +>a6 || a5 : void | E.b | E.c >a6 : E >a5 : void @@ -428,7 +428,7 @@ var rh5 = a5 || a7; // void || object is void | object var rh6 = a6 || a7; // enum || object is enum | object >rh6 : E | { a: string; } ->a6 || a7 : E | { a: string; } +>a6 || a7 : E.b | E.c | { a: string; } >a6 : E >a7 : { a: string; } @@ -488,7 +488,7 @@ var ri5 = a5 || a8; // void || array is void | array var ri6 = a6 || a8; // enum || array is enum | array >ri6 : E | string[] ->a6 || a8 : E | string[] +>a6 || a8 : E.b | E.c | string[] >a6 : E >a8 : string[] @@ -548,7 +548,7 @@ var rj5 = a5 || null; // void || null is void var rj6 = a6 || null; // enum || null is E >rj6 : E ->a6 || null : E +>a6 || null : E.b | E.c >a6 : E >null : null @@ -608,7 +608,7 @@ var rf5 = a5 || undefined; // void || undefined is void var rf6 = a6 || undefined; // enum || undefined is E >rf6 : E ->a6 || undefined : E +>a6 || undefined : E.b | E.c >a6 : E >undefined : undefined diff --git a/tests/baselines/reference/metadataOfUnion.types b/tests/baselines/reference/metadataOfUnion.types index 08afc4e81bb..542d37e2085 100644 --- a/tests/baselines/reference/metadataOfUnion.types +++ b/tests/baselines/reference/metadataOfUnion.types @@ -81,6 +81,6 @@ class D { >PropDeco : (target: Object, propKey: string | symbol) => void d: E | number; ->d : number | E +>d : number >E : E } diff --git a/tests/baselines/reference/subtypesOfUnion.errors.txt b/tests/baselines/reference/subtypesOfUnion.errors.txt index fade5377814..7cbca6cc409 100644 --- a/tests/baselines/reference/subtypesOfUnion.errors.txt +++ b/tests/baselines/reference/subtypesOfUnion.errors.txt @@ -12,21 +12,21 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOf tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(28,5): error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'string | number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(29,5): error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'string | number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(30,5): error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'string | number'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(35,5): error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(37,5): error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(39,5): error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(40,5): error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(41,5): error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(42,5): error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(43,5): error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(44,5): error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(45,5): error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(46,5): error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(47,5): error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(48,5): error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(49,5): error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(50,5): error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number | E'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(51,5): error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number | E'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(35,5): error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(37,5): error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(39,5): error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(40,5): error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(41,5): error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(42,5): error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(43,5): error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(44,5): error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(45,5): error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(46,5): error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(47,5): error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(48,5): error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(49,5): error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(50,5): error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts(51,5): error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number'. ==== tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOfUnion.ts (29 errors) ==== @@ -94,49 +94,49 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/subtypesOf foo: any; // ok foo2: string; // error ~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo2' of type 'string' is not assignable to string index type 'number'. foo3: number; // ok foo4: boolean; // error ~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo4' of type 'boolean' is not assignable to string index type 'number'. foo5: E; // ok foo6: Date; // error ~~~~~~~~~~~ -!!! error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo6' of type 'Date' is not assignable to string index type 'number'. foo7: RegExp; // error ~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo7' of type 'RegExp' is not assignable to string index type 'number'. foo8: { bar: number }; // error ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo8' of type '{ bar: number; }' is not assignable to string index type 'number'. foo9: I8; // error ~~~~~~~~~ -!!! error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo9' of type 'I8' is not assignable to string index type 'number'. foo10: A; // error ~~~~~~~~~ -!!! error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo10' of type 'A' is not assignable to string index type 'number'. foo11: A2; // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo11' of type 'A2' is not assignable to string index type 'number'. foo12: (x) => number; //error ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo12' of type '(x: any) => number' is not assignable to string index type 'number'. foo13: (x: T) => T; // error ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo13' of type '(x: T) => T' is not assignable to string index type 'number'. foo14: typeof f; // error ~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo14' of type 'typeof f' is not assignable to string index type 'number'. foo15: typeof c; // error ~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo15' of type 'typeof c' is not assignable to string index type 'number'. foo16: T; // error ~~~~~~~~~ -!!! error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo16' of type 'T' is not assignable to string index type 'number'. foo17: Object; // error ~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo17' of type 'Object' is not assignable to string index type 'number'. foo18: {}; // error ~~~~~~~~~~ -!!! error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number | E'. +!!! error TS2411: Property 'foo18' of type '{}' is not assignable to string index type 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt b/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt index 013b5d9a990..ddf5da8881a 100644 --- a/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt +++ b/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.errors.txt @@ -1,37 +1,36 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(15,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(21,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'string'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(22,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'string'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(22,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'string'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(28,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'boolean'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(29,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'boolean'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(29,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'boolean'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(35,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'Date'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(36,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'Date'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(36,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'Date'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(42,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'RegExp'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(43,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'RegExp'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(43,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'RegExp'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(49,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '{ bar: number; }'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(50,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '{ bar: number; }'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(50,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '{ bar: number; }'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(56,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'number[]'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(57,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'number[]'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(57,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'number[]'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(63,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'I8'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(64,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'I8'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(64,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'I8'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(70,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(71,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(71,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(77,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A2'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(78,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A2'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(78,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A2'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(84,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: any) => number'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(85,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: any) => number'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(85,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: any) => number'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(91,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: T) => T'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(92,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: T) => T'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(92,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: T) => T'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(99,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'E2'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(100,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'E2'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(110,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof f'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(111,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof f'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(111,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof f'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(121,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof c'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(122,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof c'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(122,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof c'. tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(128,5): error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'T'. -tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(129,5): error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'T'. +tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts(129,5): error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'T'. -==== tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts (31 errors) ==== +==== tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubtypeIfEveryConstituentTypeIsSubtype.ts (30 errors) ==== enum e { e1, e2 @@ -59,7 +58,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'string'. foo2: e | number; // error e and number both not subtype of string ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'string'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'string'. } // error cases @@ -70,7 +69,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'boolean'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'boolean'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'boolean'. } @@ -81,7 +80,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'Date'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'Date'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'Date'. } @@ -92,7 +91,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'RegExp'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'RegExp'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'RegExp'. } @@ -103,7 +102,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '{ bar: number; }'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '{ bar: number; }'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '{ bar: number; }'. } @@ -114,7 +113,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'number[]'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'number[]'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'number[]'. } @@ -125,7 +124,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'I8'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'I8'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'I8'. } class A { foo: number; } @@ -136,7 +135,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A'. } class A2 { foo: T; } @@ -147,7 +146,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'A2'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'A2'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'A2'. } @@ -158,7 +157,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: any) => number'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: any) => number'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: any) => number'. } @@ -169,7 +168,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type '(x: T) => T'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type '(x: T) => T'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type '(x: T) => T'. } @@ -180,8 +179,6 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'E2'. foo2: e | number; - ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'E2'. } @@ -196,7 +193,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof f'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof f'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof f'. } @@ -211,7 +208,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'typeof c'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'typeof c'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'typeof c'. } @@ -222,7 +219,7 @@ tests/cases/conformance/types/typeRelationships/subtypesAndSuperTypes/unionSubty !!! error TS2411: Property 'foo' of type 'string | number' is not assignable to string index type 'T'. foo2: e | number; ~~~~~~~~~~~~~~~~~ -!!! error TS2411: Property 'foo2' of type 'number | e' is not assignable to string index type 'T'. +!!! error TS2411: Property 'foo2' of type 'number' is not assignable to string index type 'T'. } interface I19 { From d2fdebe246a6c93dbf679e28f1aa1d0484d5feb0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 28 Apr 2017 13:19:01 -0700 Subject: [PATCH 017/282] Fix type-to-string handling of enum literal types --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4af13dfa21e..e1c185360d3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3051,7 +3051,7 @@ namespace ts { writePunctuation(writer, SyntaxKind.DotToken); appendSymbolNameOnly(type.symbol, writer); } - else if (getObjectFlags(type) & ObjectFlags.ClassOrInterface || type.flags & (TypeFlags.Enum | TypeFlags.TypeParameter)) { + else if (getObjectFlags(type) & ObjectFlags.ClassOrInterface || type.flags & (TypeFlags.EnumLike | TypeFlags.TypeParameter)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); } From 9e7cdb4df57a27e7b14fb4e4d866c1b48e52f1aa Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 08:37:33 -0700 Subject: [PATCH 018/282] Support string valued members in literal enums --- src/compiler/checker.ts | 86 ++++++++++++++++------------ src/compiler/diagnosticMessages.json | 4 ++ src/compiler/emitter.ts | 2 +- src/compiler/factory.ts | 2 +- src/compiler/transformers/ts.ts | 33 ++++++----- src/compiler/types.ts | 15 +++-- src/compiler/utilities.ts | 2 +- src/services/symbolDisplay.ts | 5 +- 8 files changed, 90 insertions(+), 59 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e1c185360d3..689d3e44a7c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47,6 +47,7 @@ namespace ts { let typeCount = 0; let symbolCount = 0; + let enumCount = 0; let symbolInstantiationDepth = 0; const emptyArray: any[] = []; @@ -210,8 +211,7 @@ namespace ts { const tupleTypes: GenericType[] = []; const unionTypes = createMap(); const intersectionTypes = createMap(); - const stringLiteralTypes = createMap(); - const numericLiteralTypes = createMap(); + const literalTypes = createMap(); const indexedAccessTypes = createMap(); const evolvingArrayTypes: EvolvingArrayType[] = []; @@ -4904,34 +4904,36 @@ namespace ts { return links.declaredType; } - function isLiteralEnumMember(symbol: Symbol, member: EnumMember) { + function isLiteralEnumMember(member: EnumMember) { const expr = member.initializer; if (!expr) { return !isInAmbientContext(member); } - return expr.kind === SyntaxKind.NumericLiteral || + return expr.kind === SyntaxKind.StringLiteral || expr.kind === SyntaxKind.NumericLiteral || expr.kind === SyntaxKind.PrefixUnaryExpression && (expr).operator === SyntaxKind.MinusToken && (expr).operand.kind === SyntaxKind.NumericLiteral || - expr.kind === SyntaxKind.Identifier && !!symbol.exports.get((expr).text); + expr.kind === SyntaxKind.Identifier && (nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get((expr).text)); } - function enumHasLiteralMembers(symbol: Symbol) { + function getEnumKind(symbol: Symbol): EnumKind { + const links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + let hasNonLiteralMember = false; for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { for (const member of (declaration).members) { - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === SyntaxKind.StringLiteral) { + return links.enumKind = EnumKind.Literal; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; - } - - function createEnumLiteralType(symbol: Symbol, value: number) { - const type = createLiteralType(TypeFlags.NumberLiteral | TypeFlags.EnumLiteral, value); - type.symbol = symbol; - return type; + return links.enumKind = hasNonLiteralMember ? EnumKind.Numeric : EnumKind.Literal; } function getBaseTypeOfEnumLiteralType(type: Type) { @@ -4943,17 +4945,14 @@ namespace ts { if (links.declaredType) { return links.declaredType; } - if (enumHasLiteralMembers(symbol)) { + if (getEnumKind(symbol) === EnumKind.Literal) { + enumCount++; const memberTypeList: Type[] = []; - const memberTypes: LiteralType[] = []; for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { - computeEnumMemberValues(declaration); for (const member of (declaration).members) { - const memberSymbol = getSymbolOfNode(member); - const value = getEnumMemberValue(member); - if (!memberTypes[value]) { - const memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, value); + const memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + if (!contains(memberTypeList, memberType)) { memberTypeList.push(memberType); } } @@ -4963,7 +4962,7 @@ namespace ts { for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { for (const member of (declaration).members) { - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberTypes[getEnumMemberValue(member)]; + getSymbolLinks(getSymbolOfNode(member)).declaredType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); } } } @@ -7517,8 +7516,9 @@ namespace ts { return prop.flags & SymbolFlags.Method && find(prop.declarations, decl => isClassLike(decl.parent)); } - function createLiteralType(flags: TypeFlags, value: string | number) { + function createLiteralType(flags: TypeFlags, value: string | number, symbol: Symbol) { const type = createType(flags); + type.symbol = symbol; type.value = value; return type; } @@ -7526,7 +7526,7 @@ namespace ts { function getFreshTypeOfLiteralType(type: Type) { if (type.flags & TypeFlags.StringOrNumberLiteral && !(type.flags & TypeFlags.FreshLiteral)) { if (!(type).freshType) { - const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).value); + const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).value, (type).symbol); freshType.regularType = type; (type).freshType = freshType; } @@ -7539,12 +7539,17 @@ namespace ts { return type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral ? (type).regularType : type; } - function getLiteralType(value: string | number) { - const map = typeof value === "number" ? numericLiteralTypes : stringLiteralTypes; - const text = "" + value; - let type = map.get(text); + function getLiteralType(value: string | number, enumId?: number, symbol?: Symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + const qualifier = typeof value === "number" ? "#" : "@"; + const key = enumId ? enumId + qualifier + value : qualifier + value; + let type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(typeof value === "number" ? TypeFlags.NumberLiteral : TypeFlags.StringLiteral, value)); + const flags = (typeof value === "number" ? TypeFlags.NumberLiteral : TypeFlags.StringLiteral) | (enumId ? TypeFlags.EnumLiteral : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -20716,17 +20721,22 @@ namespace ts { return undefined; } - function computeConstantValue(member: EnumMember): number { + function computeConstantValue(member: EnumMember): string | number { + const enumKind = getEnumKind(getSymbolOfNode(member.parent)); const isConstEnum = isConst(member.parent); const initializer = member.initializer; - const value = evaluate(member.initializer); + const value = enumKind === EnumKind.Literal && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); if (value !== undefined) { - if (isConstEnum && !isFinite(value)) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { error(initializer, isNaN(value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); } } + else if (enumKind === EnumKind.Literal) { + error(initializer, Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } else if (isConstEnum) { error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } @@ -20739,7 +20749,7 @@ namespace ts { } return value; - function evaluate(expr: Expression): number { + function evaluate(expr: Expression): string | number { switch (expr.kind) { case SyntaxKind.PrefixUnaryExpression: const value = evaluate((expr).operand); @@ -20770,13 +20780,15 @@ namespace ts { } } break; + case SyntaxKind.StringLiteral: + return (expr).text; case SyntaxKind.NumericLiteral: checkGrammarNumericLiteral(expr); return +(expr).text; case SyntaxKind.ParenthesizedExpression: return evaluate((expr).expression); case SyntaxKind.Identifier: - return evaluateEnumMember(expr, getSymbolOfNode(member.parent), (expr).text); + return nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), (expr).text); case SyntaxKind.ElementAccessExpression: case SyntaxKind.PropertyAccessExpression: if (isConstantMemberAccess(expr)) { @@ -22476,7 +22488,7 @@ namespace ts { return getNodeLinks(node).flags; } - function getEnumMemberValue(node: EnumMember): number { + function getEnumMemberValue(node: EnumMember): string | number { computeEnumMemberValues(node.parent); return getNodeLinks(node).enumMemberValue; } @@ -22491,7 +22503,7 @@ namespace ts { return false; } - function getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number { + function getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number { if (node.kind === SyntaxKind.EnumMember) { return getEnumMemberValue(node); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index b69adf708f2..43c1c6334cd 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1843,6 +1843,10 @@ "category": "Error", "code": 2550 }, + "Computed values are not permitted in an enum with string valued members.": { + "category": "Error", + "code": 2551 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 669c9f5dd36..0f00f664e0d 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1128,7 +1128,7 @@ namespace ts { // check if constant enum value is integer const constantValue = getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 5c7486debe3..074e6489a73 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2248,7 +2248,7 @@ namespace ts { /** * Sets the constant value to emit for an expression. */ - export function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number) { + export function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number) { const emitNode = getOrCreateEmitNode(node); emitNode.constantValue = value; return node; diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 780e519bb53..5b0623094c3 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -2498,22 +2498,27 @@ namespace ts { // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. const name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + const valueExpression = transformEnumMemberDeclarationValue(member); + const innerAssignment = createAssignment( + createElementAccess( + currentNamespaceContainerName, + name + ), + valueExpression + ); + const outerAssignment = valueExpression.kind === SyntaxKind.StringLiteral ? + innerAssignment : + createAssignment( + createElementAccess( + currentNamespaceContainerName, + innerAssignment + ), + name + ); return setTextRange( createStatement( setTextRange( - createAssignment( - createElementAccess( - currentNamespaceContainerName, - createAssignment( - createElementAccess( - currentNamespaceContainerName, - name - ), - transformEnumMemberDeclarationValue(member) - ) - ), - name - ), + outerAssignment, member ) ), @@ -3351,7 +3356,7 @@ namespace ts { return node; } - function tryGetConstEnumValue(node: Node): number { + function tryGetConstEnumValue(node: Node): string | number { if (compilerOptions.isolatedModules) { return undefined; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index f17dec4bd12..da69d64e04d 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2528,7 +2528,7 @@ namespace ts { isUnknownSymbol(symbol: Symbol): boolean; /* @internal */ getMergedSymbol(symbol: Symbol): Symbol; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; @@ -2731,7 +2731,7 @@ namespace ts { isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number; getReferencedValueDeclaration(reference: Identifier): Declaration; getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind; isOptionalParameter(node: ParameterDeclaration): boolean; @@ -2869,6 +2869,13 @@ namespace ts { isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration bindingElement?: BindingElement; // Binding element associated with property symbol exportsSomeValue?: boolean; // True if module exports some value (not just types) + enumKind?: EnumKind; // Enum declaration classification + } + + /* @internal */ + export const enum EnumKind { + Numeric, // Numeric enum (each member has a TypeFlags.Enum type) + Literal // Literal enum (each member has a TypeFlags.EnumLiteral type) } /* @internal */ @@ -2941,7 +2948,7 @@ namespace ts { resolvedSymbol?: Symbol; // Cached name resolution result resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate - enumMemberValue?: number; // Constant value of enum member + enumMemberValue?: string | number; // Constant value of enum member isVisible?: boolean; // Is this node visible containsArgumentsReference?: boolean; // Whether a function-like declaration contains an 'arguments' reference hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context @@ -3918,7 +3925,7 @@ namespace ts { commentRange?: TextRange; // The text range to use when emitting leading or trailing comments sourceMapRange?: TextRange; // The text range to use when emitting leading or trailing source mappings tokenSourceMapRanges?: TextRange[]; // The text range to use when emitting source mappings for tokens - constantValue?: number; // The constant value of an expression + constantValue?: string | number; // The constant value of an expression externalHelpersModuleName?: Identifier; // The local name for an imported helpers module helpers?: EmitHelper[]; // Emit helpers for the node } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 646a7b22e3f..8080f6985e8 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -349,7 +349,7 @@ namespace ts { Debug.fail(`Literal kind '${node.kind}' not accounted for.`); } - function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) { + export function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) { return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 41bdf4d8ada..8f61ca9c914 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -330,7 +330,10 @@ namespace ts.SymbolDisplay { displayParts.push(spacePart()); displayParts.push(operatorPart(SyntaxKind.EqualsToken)); displayParts.push(spacePart()); - displayParts.push(displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral)); + const valuePart = typeof constantValue === "number" ? + displayPart("" + constantValue, SymbolDisplayPartKind.numericLiteral) : + displayPart(getQuotedEscapedLiteralText('"', constantValue, '"'), SymbolDisplayPartKind.stringLiteral); + displayParts.push(valuePart); } } } From 1f1af2735e26ae73ebf97b29f94245693d1a1430 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 10:13:35 -0700 Subject: [PATCH 019/282] Update test --- tests/cases/conformance/enums/enumErrors.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/cases/conformance/enums/enumErrors.ts b/tests/cases/conformance/enums/enumErrors.ts index ed438bb3ed6..99de3d4bc0d 100644 --- a/tests/cases/conformance/enums/enumErrors.ts +++ b/tests/cases/conformance/enums/enumErrors.ts @@ -23,8 +23,17 @@ enum E10 { // Enum with computed member intializer of other types enum E11 { - A = '', + A = true, B = new Date(), C = window, D = {} } + +// Enum with string valued member and computed member initializers +enum E12 { + A = '', + B = new Date(), + C = window, + D = {}, + E = 1 + 1, +} From be0fc3bc986b25db417f66131b00508a9959ce86 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 10:13:52 -0700 Subject: [PATCH 020/282] Accept new baselines --- .../baselines/reference/enumErrors.errors.txt | 31 ++++++++++++++++--- tests/baselines/reference/enumErrors.js | 22 +++++++++++-- 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/tests/baselines/reference/enumErrors.errors.txt b/tests/baselines/reference/enumErrors.errors.txt index 3efa042ff38..096722fc4bd 100644 --- a/tests/baselines/reference/enumErrors.errors.txt +++ b/tests/baselines/reference/enumErrors.errors.txt @@ -3,13 +3,17 @@ tests/cases/conformance/enums/enumErrors.ts(3,6): error TS2431: Enum name cannot tests/cases/conformance/enums/enumErrors.ts(4,6): error TS2431: Enum name cannot be 'string'. tests/cases/conformance/enums/enumErrors.ts(5,6): error TS2431: Enum name cannot be 'boolean'. tests/cases/conformance/enums/enumErrors.ts(9,9): error TS2322: Type 'Number' is not assignable to type 'E5'. -tests/cases/conformance/enums/enumErrors.ts(26,9): error TS2322: Type '""' is not assignable to type 'E11'. +tests/cases/conformance/enums/enumErrors.ts(26,9): error TS2322: Type 'true' is not assignable to type 'E11'. tests/cases/conformance/enums/enumErrors.ts(27,9): error TS2322: Type 'Date' is not assignable to type 'E11'. tests/cases/conformance/enums/enumErrors.ts(28,9): error TS2304: Cannot find name 'window'. tests/cases/conformance/enums/enumErrors.ts(29,9): error TS2322: Type '{}' is not assignable to type 'E11'. +tests/cases/conformance/enums/enumErrors.ts(35,9): error TS2551: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(36,9): error TS2551: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(37,9): error TS2551: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(38,9): error TS2551: Computed values are not permitted in an enum with string valued members. -==== tests/cases/conformance/enums/enumErrors.ts (9 errors) ==== +==== tests/cases/conformance/enums/enumErrors.ts (13 errors) ==== // Enum named with PredefinedTypes enum any { } ~~~ @@ -45,9 +49,9 @@ tests/cases/conformance/enums/enumErrors.ts(29,9): error TS2322: Type '{}' is no // Enum with computed member intializer of other types enum E11 { - A = '', - ~~ -!!! error TS2322: Type '""' is not assignable to type 'E11'. + A = true, + ~~~~ +!!! error TS2322: Type 'true' is not assignable to type 'E11'. B = new Date(), ~~~~~~~~~~ !!! error TS2322: Type 'Date' is not assignable to type 'E11'. @@ -58,4 +62,21 @@ tests/cases/conformance/enums/enumErrors.ts(29,9): error TS2322: Type '{}' is no ~~ !!! error TS2322: Type '{}' is not assignable to type 'E11'. } + + // Enum with string valued member and computed member initializers + enum E12 { + A = '', + B = new Date(), + ~~~~~~~~~~ +!!! error TS2551: Computed values are not permitted in an enum with string valued members. + C = window, + ~~~~~~ +!!! error TS2551: Computed values are not permitted in an enum with string valued members. + D = {}, + ~~ +!!! error TS2551: Computed values are not permitted in an enum with string valued members. + E = 1 + 1, + ~~~~~ +!!! error TS2551: Computed values are not permitted in an enum with string valued members. + } \ No newline at end of file diff --git a/tests/baselines/reference/enumErrors.js b/tests/baselines/reference/enumErrors.js index a8ecdf2470a..17b67864c70 100644 --- a/tests/baselines/reference/enumErrors.js +++ b/tests/baselines/reference/enumErrors.js @@ -24,11 +24,20 @@ enum E10 { // Enum with computed member intializer of other types enum E11 { - A = '', + A = true, B = new Date(), C = window, D = {} } + +// Enum with string valued member and computed member initializers +enum E12 { + A = '', + B = new Date(), + C = window, + D = {}, + E = 1 + 1, +} //// [enumErrors.js] @@ -65,8 +74,17 @@ var E10; // Enum with computed member intializer of other types var E11; (function (E11) { - E11[E11["A"] = ''] = "A"; + E11[E11["A"] = true] = "A"; E11[E11["B"] = new Date()] = "B"; E11[E11["C"] = window] = "C"; E11[E11["D"] = {}] = "D"; })(E11 || (E11 = {})); +// Enum with string valued member and computed member initializers +var E12; +(function (E12) { + E12["A"] = ""; + E12[E12["B"] = 0] = "B"; + E12[E12["C"] = 0] = "C"; + E12[E12["D"] = 0] = "D"; + E12[E12["E"] = 0] = "E"; +})(E12 || (E12 = {})); From 63319d1ed99fd7f2a4c5deb7f7599310c757a161 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 15:27:25 -0700 Subject: [PATCH 021/282] Treat enums with a single literal member as literal enums --- src/compiler/checker.ts | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 689d3e44a7c..ebc5c0677b3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3047,9 +3047,14 @@ namespace ts { writeTypeReference(type, nextFlags); } else if (type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union)) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); - writePunctuation(writer, SyntaxKind.DotToken); - appendSymbolNameOnly(type.symbol, writer); + const parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent).flags & TypeFlags.Union) { + writePunctuation(writer, SyntaxKind.DotToken); + appendSymbolNameOnly(type.symbol, writer); + } } else if (getObjectFlags(type) & ObjectFlags.ClassOrInterface || type.flags & (TypeFlags.EnumLike | TypeFlags.TypeParameter)) { // The specified symbol flags need to be reinterpreted as type flags @@ -4952,23 +4957,19 @@ namespace ts { if (declaration.kind === SyntaxKind.EnumDeclaration) { for (const member of (declaration).members) { const memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; if (!contains(memberTypeList, memberType)) { memberTypeList.push(memberType); } } } } - if (memberTypeList.length > 1) { - for (const declaration of symbol.declarations) { - if (declaration.kind === SyntaxKind.EnumDeclaration) { - for (const member of (declaration).members) { - getSymbolLinks(getSymbolOfNode(member)).declaredType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); - } - } - } + if (memberTypeList.length) { const enumType = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); - enumType.flags |= TypeFlags.EnumLiteral; - enumType.symbol = symbol; + if (enumType.flags & TypeFlags.Union) { + enumType.flags |= TypeFlags.EnumLiteral; + enumType.symbol = symbol; + } return links.declaredType = enumType; } } From 72e77a80e81e66594a8f024a21c09336c97d59aa Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 15:27:42 -0700 Subject: [PATCH 022/282] Accept new baselines --- tests/baselines/reference/bestCommonTypeOfTuple.types | 4 ++-- tests/baselines/reference/computedPropertyNames47_ES5.types | 2 +- tests/baselines/reference/computedPropertyNames47_ES6.types | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.types b/tests/baselines/reference/bestCommonTypeOfTuple.types index 82c96ecb86c..d62503b57d6 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple.types @@ -98,8 +98,8 @@ var e3 = t3[2]; // any >2 : 2 var e4 = t4[3]; // number ->e4 : number | E1 | E2 ->t4[3] : number | E1 | E2 +>e4 : number +>t4[3] : number >t4 : [E1, E2, number] >3 : 3 diff --git a/tests/baselines/reference/computedPropertyNames47_ES5.types b/tests/baselines/reference/computedPropertyNames47_ES5.types index 19811ae8ec2..137f3d63d38 100644 --- a/tests/baselines/reference/computedPropertyNames47_ES5.types +++ b/tests/baselines/reference/computedPropertyNames47_ES5.types @@ -12,7 +12,7 @@ var o = { >{ [E1.x || E2.x]: 0} : { [x: number]: number; } [E1.x || E2.x]: 0 ->E1.x || E2.x : E1 | E2 +>E1.x || E2.x : E2 >E1.x : E1 >E1 : typeof E1 >x : E1 diff --git a/tests/baselines/reference/computedPropertyNames47_ES6.types b/tests/baselines/reference/computedPropertyNames47_ES6.types index 46edecb450a..04c18df83a7 100644 --- a/tests/baselines/reference/computedPropertyNames47_ES6.types +++ b/tests/baselines/reference/computedPropertyNames47_ES6.types @@ -12,7 +12,7 @@ var o = { >{ [E1.x || E2.x]: 0} : { [x: number]: number; } [E1.x || E2.x]: 0 ->E1.x || E2.x : E1 | E2 +>E1.x || E2.x : E2 >E1.x : E1 >E1 : typeof E1 >x : E1 From 106214a0e4022732ff3d7ae052be82259de3d941 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 17:57:12 -0700 Subject: [PATCH 023/282] Enum literal type is assignable to regular literal type with same value --- src/compiler/checker.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ebc5c0677b3..90ca808342c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8432,7 +8432,13 @@ namespace ts { if (target.flags & TypeFlags.Never) return false; if (target.flags & TypeFlags.Any || source.flags & TypeFlags.Never) return true; if (source.flags & TypeFlags.StringLike && target.flags & TypeFlags.String) return true; + if (source.flags & TypeFlags.StringLiteral && source.flags & TypeFlags.EnumLiteral && + target.flags & TypeFlags.StringLiteral && !(target.flags & TypeFlags.EnumLiteral) && + (source).value === (target).value) return true; if (source.flags & TypeFlags.NumberLike && target.flags & TypeFlags.Number) return true; + if (source.flags & TypeFlags.NumberLiteral && source.flags & TypeFlags.EnumLiteral && + target.flags & TypeFlags.NumberLiteral && !(target.flags & TypeFlags.EnumLiteral) && + (source).value === (target).value) return true; if (source.flags & TypeFlags.BooleanLike && target.flags & TypeFlags.Boolean) return true; if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.EnumLiteral) { @@ -8446,7 +8452,11 @@ namespace ts { if (source.flags & TypeFlags.Object && target.flags & TypeFlags.NonPrimitive) return true; if (relation === assignableRelation || relation === comparableRelation) { if (source.flags & TypeFlags.Any) return true; - if (source.flags & (TypeFlags.Number | TypeFlags.NumberLiteral) && !(source.flags & TypeFlags.EnumLiteral) && target.flags & TypeFlags.EnumLike) return true; + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (source.flags & (TypeFlags.Number | TypeFlags.NumberLiteral) && !(source.flags & TypeFlags.EnumLiteral) && ( + target.flags & TypeFlags.Enum || target.flags & TypeFlags.NumberLiteral && target.flags & TypeFlags.EnumLiteral)) return true; } return false; } From 68036c57b6381a7980b3e4eddcf8b2f5eea31d66 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 17:58:16 -0700 Subject: [PATCH 024/282] Accept new baselines --- .../typeArgumentInferenceWithObjectLiteral.errors.txt | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt b/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt index e82e7e020d0..c1352bedb9b 100644 --- a/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt +++ b/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.errors.txt @@ -1,10 +1,8 @@ -tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts(30,10): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. - Type argument candidate 'E1' is not a valid type argument because it is not a supertype of candidate '0'. tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts(35,10): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'E1' is not a valid type argument because it is not a supertype of candidate 'E2'. -==== tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts (2 errors) ==== +==== tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjectLiteral.ts (1 errors) ==== interface Computed { read(): T; write(value: T); @@ -35,9 +33,6 @@ tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithObjec var v1 = f1({ w: x => x, r: () => 0 }, 0); var v1 = f1({ w: x => x, r: () => 0 }, E1.X); var v1 = f1({ w: x => x, r: () => E1.X }, 0); - ~~ -!!! error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. -!!! error TS2453: Type argument candidate 'E1' is not a valid type argument because it is not a supertype of candidate '0'. var v2: E1; var v2 = f1({ w: x => x, r: () => E1.X }, E1.X); From 925d97dc25a22f6f4284d2721deb8fe6aee9934d Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 29 Apr 2017 18:09:36 -0700 Subject: [PATCH 025/282] Cache source and target flags in local variables --- src/compiler/checker.ts | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 90ca808342c..c88951d8f21 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8429,34 +8429,36 @@ namespace ts { } function isSimpleTypeRelatedTo(source: Type, target: Type, relation: Map, errorReporter?: ErrorReporter) { - if (target.flags & TypeFlags.Never) return false; - if (target.flags & TypeFlags.Any || source.flags & TypeFlags.Never) return true; - if (source.flags & TypeFlags.StringLike && target.flags & TypeFlags.String) return true; - if (source.flags & TypeFlags.StringLiteral && source.flags & TypeFlags.EnumLiteral && - target.flags & TypeFlags.StringLiteral && !(target.flags & TypeFlags.EnumLiteral) && + const s = source.flags; + const t = target.flags; + if (t & TypeFlags.Never) return false; + if (t & TypeFlags.Any || s & TypeFlags.Never) return true; + if (s & TypeFlags.StringLike && t & TypeFlags.String) return true; + if (s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral && + t & TypeFlags.StringLiteral && !(t & TypeFlags.EnumLiteral) && (source).value === (target).value) return true; - if (source.flags & TypeFlags.NumberLike && target.flags & TypeFlags.Number) return true; - if (source.flags & TypeFlags.NumberLiteral && source.flags & TypeFlags.EnumLiteral && - target.flags & TypeFlags.NumberLiteral && !(target.flags & TypeFlags.EnumLiteral) && + if (s & TypeFlags.NumberLike && t & TypeFlags.Number) return true; + if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && + t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) && (source).value === (target).value) return true; - if (source.flags & TypeFlags.BooleanLike && target.flags & TypeFlags.Boolean) return true; - if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.EnumLiteral) { - if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & TypeFlags.Literal && target.flags & TypeFlags.Literal && + if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true; + if (s & TypeFlags.Enum && t & TypeFlags.Enum && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & TypeFlags.EnumLiteral && t & TypeFlags.EnumLiteral) { + if (s & TypeFlags.Union && t & TypeFlags.Union && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & TypeFlags.Literal && t & TypeFlags.Literal && (source).value === (target).value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (source.flags & TypeFlags.Undefined && (!strictNullChecks || target.flags & (TypeFlags.Undefined | TypeFlags.Void))) return true; - if (source.flags & TypeFlags.Null && (!strictNullChecks || target.flags & TypeFlags.Null)) return true; - if (source.flags & TypeFlags.Object && target.flags & TypeFlags.NonPrimitive) return true; + if (s & TypeFlags.Undefined && (!strictNullChecks || t & (TypeFlags.Undefined | TypeFlags.Void))) return true; + if (s & TypeFlags.Null && (!strictNullChecks || t & TypeFlags.Null)) return true; + if (s & TypeFlags.Object && t & TypeFlags.NonPrimitive) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & TypeFlags.Any) return true; + if (s & TypeFlags.Any) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (source.flags & (TypeFlags.Number | TypeFlags.NumberLiteral) && !(source.flags & TypeFlags.EnumLiteral) && ( - target.flags & TypeFlags.Enum || target.flags & TypeFlags.NumberLiteral && target.flags & TypeFlags.EnumLiteral)) return true; + if (s & (TypeFlags.Number | TypeFlags.NumberLiteral) && !(s & TypeFlags.EnumLiteral) && ( + t & TypeFlags.Enum || t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral)) return true; } return false; } From 3a96b245315ec6e15da6d306b79b760a2fa15816 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 30 Apr 2017 15:49:14 -0700 Subject: [PATCH 026/282] Update comment --- src/compiler/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index da69d64e04d..55b5492b43e 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2968,7 +2968,7 @@ namespace ts { StringLiteral = 1 << 5, NumberLiteral = 1 << 6, BooleanLiteral = 1 << 7, - EnumLiteral = 1 << 8, // Enum literal or union of enum literals + EnumLiteral = 1 << 8, // Always combined with StringLiteral, NumberLiteral, or Union ESSymbol = 1 << 9, // Type of symbol primitive introduced in ES6 Void = 1 << 10, Undefined = 1 << 11, From 21d8e9a6fdabb37136aacf185a05ad53a76d06bd Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 30 Apr 2017 16:06:07 -0700 Subject: [PATCH 027/282] Update old test --- .../baselines/reference/enumBasics.errors.txt | 86 -------------- tests/baselines/reference/enumBasics.js | 6 +- tests/baselines/reference/enumBasics.symbols | 13 +- tests/baselines/reference/enumBasics.types | 111 +++++++++--------- tests/cases/conformance/enums/enumBasics.ts | 6 +- 5 files changed, 71 insertions(+), 151 deletions(-) delete mode 100644 tests/baselines/reference/enumBasics.errors.txt diff --git a/tests/baselines/reference/enumBasics.errors.txt b/tests/baselines/reference/enumBasics.errors.txt deleted file mode 100644 index 4d82402b8ee..00000000000 --- a/tests/baselines/reference/enumBasics.errors.txt +++ /dev/null @@ -1,86 +0,0 @@ -tests/cases/conformance/enums/enumBasics.ts(13,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'e' must be of type 'typeof E1', but here has type '{ readonly [n: number]: string; readonly A: E1; readonly B: E1; readonly C: E1; }'. - - -==== tests/cases/conformance/enums/enumBasics.ts (1 errors) ==== - // Enum without initializers have first member = 0 and successive members = N + 1 - enum E1 { - A, - B, - C - } - - // Enum type is a subtype of Number - var x: number = E1.A; - - // Enum object type is anonymous with properties of the enum type and numeric indexer - var e = E1; - var e: { - ~ -!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'e' must be of type 'typeof E1', but here has type '{ readonly [n: number]: string; readonly A: E1; readonly B: E1; readonly C: E1; }'. - readonly A: E1; - readonly B: E1; - readonly C: E1; - readonly [n: number]: string; - }; - var e: typeof E1; - - // Reverse mapping of enum returns string name of property - var s = E1[e.A]; - var s: string; - - - // Enum with only constant members - enum E2 { - A = 1, B = 2, C = 3 - } - - // Enum with only computed members - enum E3 { - X = 'foo'.length, Y = 4 + 3, Z = +'foo' - } - - // Enum with constant members followed by computed members - enum E4 { - X = 0, Y, Z = 'foo'.length - } - - // Enum with > 2 constant members with no initializer for first member, non zero initializer for second element - enum E5 { - A, - B = 3, - C // 4 - } - - enum E6 { - A, - B = 0, - C // 1 - } - - // Enum with computed member initializer of type 'any' - enum E7 { - A = 'foo'['foo'] - } - - // Enum with computed member initializer of type number - enum E8 { - B = 'foo'['foo'] - } - - //Enum with computed member intializer of same enum type - enum E9 { - A, - B = A - } - - // (refer to .js to validate) - // Enum constant members are propagated - var doNotPropagate = [ - E8.B, E7.A, E4.Z, E3.X, E3.Y, E3.Z - ]; - // Enum computed members are not propagated - var doPropagate = [ - E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C - ]; - - \ No newline at end of file diff --git a/tests/baselines/reference/enumBasics.js b/tests/baselines/reference/enumBasics.js index 4ac41c0f3d1..3db9bc566c3 100644 --- a/tests/baselines/reference/enumBasics.js +++ b/tests/baselines/reference/enumBasics.js @@ -12,9 +12,9 @@ var x: number = E1.A; // Enum object type is anonymous with properties of the enum type and numeric indexer var e = E1; var e: { - readonly A: E1; - readonly B: E1; - readonly C: E1; + readonly A: E1.A; + readonly B: E1.B; + readonly C: E1.C; readonly [n: number]: string; }; var e: typeof E1; diff --git a/tests/baselines/reference/enumBasics.symbols b/tests/baselines/reference/enumBasics.symbols index ce81a80ca5f..948c1711837 100644 --- a/tests/baselines/reference/enumBasics.symbols +++ b/tests/baselines/reference/enumBasics.symbols @@ -28,17 +28,20 @@ var e = E1; var e: { >e : Symbol(e, Decl(enumBasics.ts, 11, 3), Decl(enumBasics.ts, 12, 3), Decl(enumBasics.ts, 18, 3)) - readonly A: E1; + readonly A: E1.A; >A : Symbol(A, Decl(enumBasics.ts, 12, 8)) >E1 : Symbol(E1, Decl(enumBasics.ts, 0, 0)) +>A : Symbol(E1.A, Decl(enumBasics.ts, 1, 9)) - readonly B: E1; ->B : Symbol(B, Decl(enumBasics.ts, 13, 19)) + readonly B: E1.B; +>B : Symbol(B, Decl(enumBasics.ts, 13, 21)) >E1 : Symbol(E1, Decl(enumBasics.ts, 0, 0)) +>B : Symbol(E1.B, Decl(enumBasics.ts, 2, 6)) - readonly C: E1; ->C : Symbol(C, Decl(enumBasics.ts, 14, 19)) + readonly C: E1.C; +>C : Symbol(C, Decl(enumBasics.ts, 14, 21)) >E1 : Symbol(E1, Decl(enumBasics.ts, 0, 0)) +>C : Symbol(E1.C, Decl(enumBasics.ts, 3, 6)) readonly [n: number]: string; >n : Symbol(n, Decl(enumBasics.ts, 16, 14)) diff --git a/tests/baselines/reference/enumBasics.types b/tests/baselines/reference/enumBasics.types index 9e68b06bc3e..c2e1ac94fdf 100644 --- a/tests/baselines/reference/enumBasics.types +++ b/tests/baselines/reference/enumBasics.types @@ -4,21 +4,21 @@ enum E1 { >E1 : E1 A, ->A : E1 +>A : E1.A B, ->B : E1 +>B : E1.B C ->C : E1 +>C : E1.C } // Enum type is a subtype of Number var x: number = E1.A; >x : number ->E1.A : E1 +>E1.A : E1.A >E1 : typeof E1 ->A : E1 +>A : E1.A // Enum object type is anonymous with properties of the enum type and numeric indexer var e = E1; @@ -28,17 +28,20 @@ var e = E1; var e: { >e : typeof E1 - readonly A: E1; ->A : E1 ->E1 : E1 + readonly A: E1.A; +>A : E1.A +>E1 : any +>A : E1.A - readonly B: E1; ->B : E1 ->E1 : E1 + readonly B: E1.B; +>B : E1.B +>E1 : any +>B : E1.B - readonly C: E1; ->C : E1 ->E1 : E1 + readonly C: E1.C; +>C : E1.C +>E1 : any +>C : E1.C readonly [n: number]: string; >n : number @@ -53,9 +56,9 @@ var s = E1[e.A]; >s : string >E1[e.A] : string >E1 : typeof E1 ->e.A : E1 +>e.A : E1.A >e : typeof E1 ->A : E1 +>A : E1.A var s: string; >s : string @@ -66,12 +69,12 @@ enum E2 { >E2 : E2 A = 1, B = 2, C = 3 ->A : E2 ->1 : number ->B : E2 ->2 : number ->C : E2 ->3 : number +>A : E2.A +>1 : 1 +>B : E2.B +>2 : 2 +>C : E2.C +>3 : 3 } // Enum with only computed members @@ -81,15 +84,15 @@ enum E3 { X = 'foo'.length, Y = 4 + 3, Z = +'foo' >X : E3 >'foo'.length : number ->'foo' : string +>'foo' : "foo" >length : number >Y : E3 >4 + 3 : number ->4 : number ->3 : number +>4 : 4 +>3 : 3 >Z : E3 >+'foo' : number ->'foo' : string +>'foo' : "foo" } // Enum with constant members followed by computed members @@ -98,11 +101,11 @@ enum E4 { X = 0, Y, Z = 'foo'.length >X : E4 ->0 : number +>0 : 0 >Y : E4 >Z : E4 >'foo'.length : number ->'foo' : string +>'foo' : "foo" >length : number } @@ -111,28 +114,28 @@ enum E5 { >E5 : E5 A, ->A : E5 +>A : E5.A B = 3, ->B : E5 ->3 : number +>B : E5.B +>3 : 3 C // 4 ->C : E5 +>C : E5.C } enum E6 { >E6 : E6 A, ->A : E6 +>A : E6.A B = 0, ->B : E6 ->0 : number +>B : E6.A +>0 : 0 C // 1 ->C : E6 +>C : E6.C } // Enum with computed member initializer of type 'any' @@ -142,8 +145,8 @@ enum E7 { A = 'foo'['foo'] >A : E7 >'foo'['foo'] : any ->'foo' : string ->'foo' : string +>'foo' : "foo" +>'foo' : "foo" } // Enum with computed member initializer of type number @@ -153,8 +156,8 @@ enum E8 { B = 'foo'['foo'] >B : E8 >'foo'['foo'] : any ->'foo' : string ->'foo' : string +>'foo' : "foo" +>'foo' : "foo" } //Enum with computed member intializer of same enum type @@ -198,8 +201,8 @@ var doNotPropagate = [ ]; // Enum computed members are not propagated var doPropagate = [ ->doPropagate : (E5 | E6 | E9)[] ->[ E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C] : (E5 | E6 | E9)[] +>doPropagate : (E9 | E6 | E5)[] +>[ E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C] : (E9 | E6 | E5)[] E9.A, E9.B, E6.B, E6.C, E6.A, E5.A, E5.B, E5.C >E9.A : E9 @@ -208,24 +211,24 @@ var doPropagate = [ >E9.B : E9 >E9 : typeof E9 >B : E9 ->E6.B : E6 +>E6.B : E6.A >E6 : typeof E6 ->B : E6 ->E6.C : E6 +>B : E6.A +>E6.C : E6.C >E6 : typeof E6 ->C : E6 ->E6.A : E6 +>C : E6.C +>E6.A : E6.A >E6 : typeof E6 ->A : E6 ->E5.A : E5 +>A : E6.A +>E5.A : E5.A >E5 : typeof E5 ->A : E5 ->E5.B : E5 +>A : E5.A +>E5.B : E5.B >E5 : typeof E5 ->B : E5 ->E5.C : E5 +>B : E5.B +>E5.C : E5.C >E5 : typeof E5 ->C : E5 +>C : E5.C ]; diff --git a/tests/cases/conformance/enums/enumBasics.ts b/tests/cases/conformance/enums/enumBasics.ts index 1e134540713..0a0f9d920cb 100644 --- a/tests/cases/conformance/enums/enumBasics.ts +++ b/tests/cases/conformance/enums/enumBasics.ts @@ -11,9 +11,9 @@ var x: number = E1.A; // Enum object type is anonymous with properties of the enum type and numeric indexer var e = E1; var e: { - readonly A: E1; - readonly B: E1; - readonly C: E1; + readonly A: E1.A; + readonly B: E1.B; + readonly C: E1.C; readonly [n: number]: string; }; var e: typeof E1; From 6548bcf104d608740ba37d179f6d0290f63e7301 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 30 Apr 2017 16:06:26 -0700 Subject: [PATCH 028/282] Add new tests --- .../baselines/reference/enumClassification.js | 308 ++++++++++++++ .../reference/enumClassification.symbols | 167 ++++++++ .../reference/enumClassification.types | 196 +++++++++ .../reference/stringEnumLiteralTypes1.js | 178 ++++++++ .../reference/stringEnumLiteralTypes1.symbols | 353 ++++++++++++++++ .../reference/stringEnumLiteralTypes1.types | 383 ++++++++++++++++++ .../reference/stringEnumLiteralTypes2.js | 178 ++++++++ .../reference/stringEnumLiteralTypes2.symbols | 353 ++++++++++++++++ .../reference/stringEnumLiteralTypes2.types | 383 ++++++++++++++++++ .../stringEnumLiteralTypes3.errors.txt | 166 ++++++++ .../reference/stringEnumLiteralTypes3.js | 225 ++++++++++ .../conformance/enums/enumClassification.ts | 80 ++++ .../types/literal/stringEnumLiteralTypes1.ts | 99 +++++ .../types/literal/stringEnumLiteralTypes2.ts | 101 +++++ .../types/literal/stringEnumLiteralTypes3.ts | 119 ++++++ 15 files changed, 3289 insertions(+) create mode 100644 tests/baselines/reference/enumClassification.js create mode 100644 tests/baselines/reference/enumClassification.symbols create mode 100644 tests/baselines/reference/enumClassification.types create mode 100644 tests/baselines/reference/stringEnumLiteralTypes1.js create mode 100644 tests/baselines/reference/stringEnumLiteralTypes1.symbols create mode 100644 tests/baselines/reference/stringEnumLiteralTypes1.types create mode 100644 tests/baselines/reference/stringEnumLiteralTypes2.js create mode 100644 tests/baselines/reference/stringEnumLiteralTypes2.symbols create mode 100644 tests/baselines/reference/stringEnumLiteralTypes2.types create mode 100644 tests/baselines/reference/stringEnumLiteralTypes3.errors.txt create mode 100644 tests/baselines/reference/stringEnumLiteralTypes3.js create mode 100644 tests/cases/conformance/enums/enumClassification.ts create mode 100644 tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts create mode 100644 tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts create mode 100644 tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts diff --git a/tests/baselines/reference/enumClassification.js b/tests/baselines/reference/enumClassification.js new file mode 100644 index 00000000000..f1532300027 --- /dev/null +++ b/tests/baselines/reference/enumClassification.js @@ -0,0 +1,308 @@ +//// [enumClassification.ts] +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { + A +} + +enum E02 { + A = 123 +} + +enum E03 { + A = "hello" +} + +enum E04 { + A, + B, + C +} + +enum E05 { + A, + B = 10, + C +} + +enum E06 { + A = "one", + B = "two", + C = "three" +} + +enum E07 { + A, + B, + C = "hi", + D = 10, + E, + F = "bye" +} + +enum E08 { + A = 10, + B = "hello", + C = A, + D = B, + E = C, +} + +// Examples of numeric enum types with only constant members + +enum E10 {} + +enum E11 { + A = +0, + B, + C +} + +enum E12 { + A = 1 << 0, + B = 1 << 1, + C = 1 << 2 +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { + A = "foo".length, + B = A + 1, + C = +"123", + D = Math.sin(1) +} + + +//// [enumClassification.js] +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. +// Examples of literal enum types +var E01; +(function (E01) { + E01[E01["A"] = 0] = "A"; +})(E01 || (E01 = {})); +var E02; +(function (E02) { + E02[E02["A"] = 123] = "A"; +})(E02 || (E02 = {})); +var E03; +(function (E03) { + E03["A"] = "hello"; +})(E03 || (E03 = {})); +var E04; +(function (E04) { + E04[E04["A"] = 0] = "A"; + E04[E04["B"] = 1] = "B"; + E04[E04["C"] = 2] = "C"; +})(E04 || (E04 = {})); +var E05; +(function (E05) { + E05[E05["A"] = 0] = "A"; + E05[E05["B"] = 10] = "B"; + E05[E05["C"] = 11] = "C"; +})(E05 || (E05 = {})); +var E06; +(function (E06) { + E06["A"] = "one"; + E06["B"] = "two"; + E06["C"] = "three"; +})(E06 || (E06 = {})); +var E07; +(function (E07) { + E07[E07["A"] = 0] = "A"; + E07[E07["B"] = 1] = "B"; + E07["C"] = "hi"; + E07[E07["D"] = 10] = "D"; + E07[E07["E"] = 11] = "E"; + E07["F"] = "bye"; +})(E07 || (E07 = {})); +var E08; +(function (E08) { + E08[E08["A"] = 10] = "A"; + E08["B"] = "hello"; + E08[E08["C"] = 10] = "C"; + E08["D"] = "hello"; + E08[E08["E"] = 10] = "E"; +})(E08 || (E08 = {})); +// Examples of numeric enum types with only constant members +var E10; +(function (E10) { +})(E10 || (E10 = {})); +var E11; +(function (E11) { + E11[E11["A"] = 0] = "A"; + E11[E11["B"] = 1] = "B"; + E11[E11["C"] = 2] = "C"; +})(E11 || (E11 = {})); +var E12; +(function (E12) { + E12[E12["A"] = 1] = "A"; + E12[E12["B"] = 2] = "B"; + E12[E12["C"] = 4] = "C"; +})(E12 || (E12 = {})); +// Examples of numeric enum types with constant and computed members +var E20; +(function (E20) { + E20[E20["A"] = "foo".length] = "A"; + E20[E20["B"] = E20.A + 1] = "B"; + E20[E20["C"] = +"123"] = "C"; + E20[E20["D"] = Math.sin(1)] = "D"; +})(E20 || (E20 = {})); + + +//// [enumClassification.d.ts] +declare enum E01 { + A = 0, +} +declare enum E02 { + A = 123, +} +declare enum E03 { + A = hello, +} +declare enum E04 { + A = 0, + B = 1, + C = 2, +} +declare enum E05 { + A = 0, + B = 10, + C = 11, +} +declare enum E06 { + A = one, + B = two, + C = three, +} +declare enum E07 { + A = 0, + B = 1, + C = hi, + D = 10, + E = 11, + F = bye, +} +declare enum E08 { + A = 10, + B = hello, + C = 10, + D = hello, + E = 10, +} +declare enum E10 { +} +declare enum E11 { + A = 0, + B = 1, + C = 2, +} +declare enum E12 { + A = 1, + B = 2, + C = 4, +} +declare enum E20 { + A, + B, + C, + D, +} + + +//// [DtsFileErrors] + + +tests/cases/conformance/enums/enumClassification.d.ts(8,9): error TS1066: In ambient enum declarations member initializer must be constant expression. +tests/cases/conformance/enums/enumClassification.d.ts(21,9): error TS1066: In ambient enum declarations member initializer must be constant expression. +tests/cases/conformance/enums/enumClassification.d.ts(22,9): error TS1066: In ambient enum declarations member initializer must be constant expression. +tests/cases/conformance/enums/enumClassification.d.ts(23,9): error TS1066: In ambient enum declarations member initializer must be constant expression. +tests/cases/conformance/enums/enumClassification.d.ts(28,9): error TS1066: In ambient enum declarations member initializer must be constant expression. +tests/cases/conformance/enums/enumClassification.d.ts(31,9): error TS1066: In ambient enum declarations member initializer must be constant expression. +tests/cases/conformance/enums/enumClassification.d.ts(35,9): error TS1066: In ambient enum declarations member initializer must be constant expression. +tests/cases/conformance/enums/enumClassification.d.ts(37,9): error TS1066: In ambient enum declarations member initializer must be constant expression. + + +==== tests/cases/conformance/enums/enumClassification.d.ts (8 errors) ==== + declare enum E01 { + A = 0, + } + declare enum E02 { + A = 123, + } + declare enum E03 { + A = hello, + ~~~~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + } + declare enum E04 { + A = 0, + B = 1, + C = 2, + } + declare enum E05 { + A = 0, + B = 10, + C = 11, + } + declare enum E06 { + A = one, + ~~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + B = two, + ~~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + C = three, + ~~~~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + } + declare enum E07 { + A = 0, + B = 1, + C = hi, + ~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + D = 10, + E = 11, + F = bye, + ~~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + } + declare enum E08 { + A = 10, + B = hello, + ~~~~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + C = 10, + D = hello, + ~~~~~ +!!! error TS1066: In ambient enum declarations member initializer must be constant expression. + E = 10, + } + declare enum E10 { + } + declare enum E11 { + A = 0, + B = 1, + C = 2, + } + declare enum E12 { + A = 1, + B = 2, + C = 4, + } + declare enum E20 { + A, + B, + C, + D, + } + \ No newline at end of file diff --git a/tests/baselines/reference/enumClassification.symbols b/tests/baselines/reference/enumClassification.symbols new file mode 100644 index 00000000000..119162e26a1 --- /dev/null +++ b/tests/baselines/reference/enumClassification.symbols @@ -0,0 +1,167 @@ +=== tests/cases/conformance/enums/enumClassification.ts === +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { +>E01 : Symbol(E01, Decl(enumClassification.ts, 0, 0)) + + A +>A : Symbol(E01.A, Decl(enumClassification.ts, 7, 10)) +} + +enum E02 { +>E02 : Symbol(E02, Decl(enumClassification.ts, 9, 1)) + + A = 123 +>A : Symbol(E02.A, Decl(enumClassification.ts, 11, 10)) +} + +enum E03 { +>E03 : Symbol(E03, Decl(enumClassification.ts, 13, 1)) + + A = "hello" +>A : Symbol(E03.A, Decl(enumClassification.ts, 15, 10)) +} + +enum E04 { +>E04 : Symbol(E04, Decl(enumClassification.ts, 17, 1)) + + A, +>A : Symbol(E04.A, Decl(enumClassification.ts, 19, 10)) + + B, +>B : Symbol(E04.B, Decl(enumClassification.ts, 20, 6)) + + C +>C : Symbol(E04.C, Decl(enumClassification.ts, 21, 6)) +} + +enum E05 { +>E05 : Symbol(E05, Decl(enumClassification.ts, 23, 1)) + + A, +>A : Symbol(E05.A, Decl(enumClassification.ts, 25, 10)) + + B = 10, +>B : Symbol(E05.B, Decl(enumClassification.ts, 26, 6)) + + C +>C : Symbol(E05.C, Decl(enumClassification.ts, 27, 11)) +} + +enum E06 { +>E06 : Symbol(E06, Decl(enumClassification.ts, 29, 1)) + + A = "one", +>A : Symbol(E06.A, Decl(enumClassification.ts, 31, 10)) + + B = "two", +>B : Symbol(E06.B, Decl(enumClassification.ts, 32, 14)) + + C = "three" +>C : Symbol(E06.C, Decl(enumClassification.ts, 33, 14)) +} + +enum E07 { +>E07 : Symbol(E07, Decl(enumClassification.ts, 35, 1)) + + A, +>A : Symbol(E07.A, Decl(enumClassification.ts, 37, 10)) + + B, +>B : Symbol(E07.B, Decl(enumClassification.ts, 38, 6)) + + C = "hi", +>C : Symbol(E07.C, Decl(enumClassification.ts, 39, 6)) + + D = 10, +>D : Symbol(E07.D, Decl(enumClassification.ts, 40, 13)) + + E, +>E : Symbol(E07.E, Decl(enumClassification.ts, 41, 11)) + + F = "bye" +>F : Symbol(E07.F, Decl(enumClassification.ts, 42, 6)) +} + +enum E08 { +>E08 : Symbol(E08, Decl(enumClassification.ts, 44, 1)) + + A = 10, +>A : Symbol(E08.A, Decl(enumClassification.ts, 46, 10)) + + B = "hello", +>B : Symbol(E08.B, Decl(enumClassification.ts, 47, 11)) + + C = A, +>C : Symbol(E08.C, Decl(enumClassification.ts, 48, 16)) +>A : Symbol(E08.A, Decl(enumClassification.ts, 46, 10)) + + D = B, +>D : Symbol(E08.D, Decl(enumClassification.ts, 49, 10)) +>B : Symbol(E08.B, Decl(enumClassification.ts, 47, 11)) + + E = C, +>E : Symbol(E08.E, Decl(enumClassification.ts, 50, 10)) +>C : Symbol(E08.C, Decl(enumClassification.ts, 48, 16)) +} + +// Examples of numeric enum types with only constant members + +enum E10 {} +>E10 : Symbol(E10, Decl(enumClassification.ts, 52, 1)) + +enum E11 { +>E11 : Symbol(E11, Decl(enumClassification.ts, 56, 11)) + + A = +0, +>A : Symbol(E11.A, Decl(enumClassification.ts, 58, 10)) + + B, +>B : Symbol(E11.B, Decl(enumClassification.ts, 59, 11)) + + C +>C : Symbol(E11.C, Decl(enumClassification.ts, 60, 6)) +} + +enum E12 { +>E12 : Symbol(E12, Decl(enumClassification.ts, 62, 1)) + + A = 1 << 0, +>A : Symbol(E12.A, Decl(enumClassification.ts, 64, 10)) + + B = 1 << 1, +>B : Symbol(E12.B, Decl(enumClassification.ts, 65, 15)) + + C = 1 << 2 +>C : Symbol(E12.C, Decl(enumClassification.ts, 66, 15)) +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { +>E20 : Symbol(E20, Decl(enumClassification.ts, 68, 1)) + + A = "foo".length, +>A : Symbol(E20.A, Decl(enumClassification.ts, 72, 10)) +>"foo".length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + B = A + 1, +>B : Symbol(E20.B, Decl(enumClassification.ts, 73, 21)) +>A : Symbol(E20.A, Decl(enumClassification.ts, 72, 10)) + + C = +"123", +>C : Symbol(E20.C, Decl(enumClassification.ts, 74, 14)) + + D = Math.sin(1) +>D : Symbol(E20.D, Decl(enumClassification.ts, 75, 15)) +>Math.sin : Symbol(Math.sin, Decl(lib.d.ts, --, --)) +>Math : Symbol(Math, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>sin : Symbol(Math.sin, Decl(lib.d.ts, --, --)) +} + diff --git a/tests/baselines/reference/enumClassification.types b/tests/baselines/reference/enumClassification.types new file mode 100644 index 00000000000..d0581c7fcae --- /dev/null +++ b/tests/baselines/reference/enumClassification.types @@ -0,0 +1,196 @@ +=== tests/cases/conformance/enums/enumClassification.ts === +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { +>E01 : E01 + + A +>A : E01 +} + +enum E02 { +>E02 : E02 + + A = 123 +>A : E02 +>123 : 123 +} + +enum E03 { +>E03 : E03 + + A = "hello" +>A : E03 +>"hello" : "hello" +} + +enum E04 { +>E04 : E04 + + A, +>A : E04.A + + B, +>B : E04.B + + C +>C : E04.C +} + +enum E05 { +>E05 : E05 + + A, +>A : E05.A + + B = 10, +>B : E05.B +>10 : 10 + + C +>C : E05.C +} + +enum E06 { +>E06 : E06 + + A = "one", +>A : E06.A +>"one" : "one" + + B = "two", +>B : E06.B +>"two" : "two" + + C = "three" +>C : E06.C +>"three" : "three" +} + +enum E07 { +>E07 : E07 + + A, +>A : E07.A + + B, +>B : E07.B + + C = "hi", +>C : E07.C +>"hi" : "hi" + + D = 10, +>D : E07.D +>10 : 10 + + E, +>E : E07.E + + F = "bye" +>F : E07.F +>"bye" : "bye" +} + +enum E08 { +>E08 : E08 + + A = 10, +>A : E08.A +>10 : 10 + + B = "hello", +>B : E08.B +>"hello" : "hello" + + C = A, +>C : E08.A +>A : E08.A + + D = B, +>D : E08.B +>B : E08.B + + E = C, +>E : E08.A +>C : E08.A +} + +// Examples of numeric enum types with only constant members + +enum E10 {} +>E10 : E10 + +enum E11 { +>E11 : E11 + + A = +0, +>A : E11 +>+0 : number +>0 : 0 + + B, +>B : E11 + + C +>C : E11 +} + +enum E12 { +>E12 : E12 + + A = 1 << 0, +>A : E12 +>1 << 0 : number +>1 : 1 +>0 : 0 + + B = 1 << 1, +>B : E12 +>1 << 1 : number +>1 : 1 +>1 : 1 + + C = 1 << 2 +>C : E12 +>1 << 2 : number +>1 : 1 +>2 : 2 +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { +>E20 : E20 + + A = "foo".length, +>A : E20 +>"foo".length : number +>"foo" : "foo" +>length : number + + B = A + 1, +>B : E20 +>A + 1 : number +>A : E20 +>1 : 1 + + C = +"123", +>C : E20 +>+"123" : number +>"123" : "123" + + D = Math.sin(1) +>D : E20 +>Math.sin(1) : number +>Math.sin : (x: number) => number +>Math : Math +>sin : (x: number) => number +>1 : 1 +} + diff --git a/tests/baselines/reference/stringEnumLiteralTypes1.js b/tests/baselines/reference/stringEnumLiteralTypes1.js new file mode 100644 index 00000000000..4acf2ada1a8 --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes1.js @@ -0,0 +1,178 @@ +//// [stringEnumLiteralTypes1.ts] +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} + +//// [stringEnumLiteralTypes1.js] +; +function f1() { + var a; + var a; + var a; + var a; +} +function f2(a, b, c) { + b = a; + c = a; + c = b; +} +function f3(a, b) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} +function f5(a, b, c) { + var z1 = g("yes" /* Yes */); + var z2 = g("no" /* No */); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} +function assertNever(x) { + throw new Error("Unexpected value"); +} +function f10(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } +} +function f11(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } + return assertNever(x); +} +function f12(x) { + if (x) { + x; + } + else { + x; + } +} +function f13(x) { + if (x === "yes" /* Yes */) { + x; + } + else { + x; + } +} +function f20(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } +} +function f21(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } + return assertNever(x); +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes1.symbols b/tests/baselines/reference/stringEnumLiteralTypes1.symbols new file mode 100644 index 00000000000..66c25aab85c --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes1.symbols @@ -0,0 +1,353 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes1.ts, 0, 19)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +type YesNo = Choice.Yes | Choice.No; +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +type NoYes = Choice.No | Choice.Yes; +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes1.ts, 2, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes1.ts, 0, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +function f1() { +>f1 : Symbol(f1, Decl(stringEnumLiteralTypes1.ts, 4, 60)) + + var a: YesNo; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + var a: NoYes; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes1.ts, 2, 36)) + + var a: Choice.Yes | Choice.No; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + + var a: Choice.No | Choice.Yes; +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 7, 7), Decl(stringEnumLiteralTypes1.ts, 8, 7), Decl(stringEnumLiteralTypes1.ts, 9, 7), Decl(stringEnumLiteralTypes1.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : Symbol(f2, Decl(stringEnumLiteralTypes1.ts, 11, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 13, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 13, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 13, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) + + b = a; +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 13, 21)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 13, 12)) + + c = a; +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 13, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 13, 12)) + + c = b; +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 13, 38)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 13, 21)) +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : Symbol(f3, Decl(stringEnumLiteralTypes1.ts, 17, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + var x = a + b; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 20, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a == b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a != b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a === b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a !== b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a > b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a < b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a >= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = a <= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) + + var y = !b; +>y : Symbol(y, Decl(stringEnumLiteralTypes1.ts, 21, 7), Decl(stringEnumLiteralTypes1.ts, 22, 7), Decl(stringEnumLiteralTypes1.ts, 23, 7), Decl(stringEnumLiteralTypes1.ts, 24, 7), Decl(stringEnumLiteralTypes1.ts, 25, 7), Decl(stringEnumLiteralTypes1.ts, 26, 7), Decl(stringEnumLiteralTypes1.ts, 27, 7), Decl(stringEnumLiteralTypes1.ts, 28, 7), Decl(stringEnumLiteralTypes1.ts, 29, 7)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 19, 26)) +} + +declare function g(x: Choice.Yes): string; +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 32, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + +declare function g(x: Choice.No): boolean; +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 33, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + +declare function g(x: Choice): number; +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 34, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : Symbol(f5, Decl(stringEnumLiteralTypes1.ts, 34, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 36, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 36, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 36, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) + + var z1 = g(Choice.Yes); +>z1 : Symbol(z1, Decl(stringEnumLiteralTypes1.ts, 37, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + var z2 = g(Choice.No); +>z2 : Symbol(z2, Decl(stringEnumLiteralTypes1.ts, 38, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + + var z3 = g(a); +>z3 : Symbol(z3, Decl(stringEnumLiteralTypes1.ts, 39, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 36, 12)) + + var z4 = g(b); +>z4 : Symbol(z4, Decl(stringEnumLiteralTypes1.ts, 40, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 36, 21)) + + var z5 = g(c); +>z5 : Symbol(z5, Decl(stringEnumLiteralTypes1.ts, 41, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes1.ts, 30, 1), Decl(stringEnumLiteralTypes1.ts, 32, 42), Decl(stringEnumLiteralTypes1.ts, 33, 42)) +>c : Symbol(c, Decl(stringEnumLiteralTypes1.ts, 36, 38)) +} + +function assertNever(x: never): never { +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes1.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 44, 21)) + + throw new Error("Unexpected value"); +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +} + +function f10(x: YesNo) { +>f10 : Symbol(f10, Decl(stringEnumLiteralTypes1.ts, 46, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 48, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 48, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + } +} + +function f11(x: YesNo) { +>f11 : Symbol(f11, Decl(stringEnumLiteralTypes1.ts, 53, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 55, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes1.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 55, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes1.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 55, 13)) +} + +function f12(x: UnknownYesNo) { +>f12 : Symbol(f12, Decl(stringEnumLiteralTypes1.ts, 61, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) + + if (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 63, 13)) + } +} + +function f13(x: UnknownYesNo) { +>f13 : Symbol(f13, Decl(stringEnumLiteralTypes1.ts, 70, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes1.ts, 3, 36)) + + if (x === Choice.Yes) { +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 72, 13)) + } +} + +type Item = +>Item : Symbol(Item, Decl(stringEnumLiteralTypes1.ts, 79, 1)) + + { kind: Choice.Yes, a: string } | +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) + + { kind: Choice.No, b: string }; +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 83, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) + +function f20(x: Item) { +>f20 : Symbol(f20, Decl(stringEnumLiteralTypes1.ts, 83, 35)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes1.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 85, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) + } +} + +function f21(x: Item) { +>f21 : Symbol(f21, Decl(stringEnumLiteralTypes1.ts, 90, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes1.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes1.ts, 82, 5), Decl(stringEnumLiteralTypes1.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes1.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes1.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes1.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes1.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes1.ts, 83, 22)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes1.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes1.ts, 92, 13)) +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes1.types b/tests/baselines/reference/stringEnumLiteralTypes1.types new file mode 100644 index 00000000000..b5d70ed501f --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes1.types @@ -0,0 +1,383 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Choice +>Unknown : Choice.Unknown +>"" : "" +>Yes : Choice.Yes +>"yes" : "yes" +>No : Choice.No +>"no" : "no" + +type YesNo = Choice.Yes | Choice.No; +>YesNo : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +type NoYes = Choice.No | Choice.Yes; +>NoYes : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Choice +>Choice : any +>Unknown : Choice.Unknown +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +function f1() { +>f1 : () => void + + var a: YesNo; +>a : YesNo +>YesNo : YesNo + + var a: NoYes; +>a : YesNo +>NoYes : YesNo + + var a: Choice.Yes | Choice.No; +>a : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + + var a: Choice.No | Choice.Yes; +>a : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + b = a; +>b = a : YesNo +>b : Choice +>a : YesNo + + c = a; +>c = a : YesNo +>c : Choice +>a : YesNo + + c = b; +>c = b : YesNo +>c : Choice +>b : YesNo +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : (a: Choice.Yes, b: YesNo) => void +>a : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>b : YesNo +>YesNo : YesNo + + var x = a + b; +>x : string +>a + b : string +>a : Choice.Yes +>b : YesNo + + var y = a == b; +>y : boolean +>a == b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a != b; +>y : boolean +>a != b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a === b; +>y : boolean +>a === b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a !== b; +>y : boolean +>a !== b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a > b; +>y : boolean +>a > b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a < b; +>y : boolean +>a < b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a >= b; +>y : boolean +>a >= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a <= b; +>y : boolean +>a <= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = !b; +>y : boolean +>!b : boolean +>b : YesNo +} + +declare function g(x: Choice.Yes): string; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.Yes +>Choice : any +>Yes : Choice.Yes + +declare function g(x: Choice.No): boolean; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.No +>Choice : any +>No : Choice.No + +declare function g(x: Choice): number; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice +>Choice : Choice + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + var z1 = g(Choice.Yes); +>z1 : string +>g(Choice.Yes) : string +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + var z2 = g(Choice.No); +>z2 : boolean +>g(Choice.No) : boolean +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No + + var z3 = g(a); +>z3 : number +>g(a) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>a : YesNo + + var z4 = g(b); +>z4 : number +>g(b) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>b : Choice + + var z5 = g(c); +>z5 : number +>g(c) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>c : Choice +} + +function assertNever(x: never): never { +>assertNever : (x: never) => never +>x : never + + throw new Error("Unexpected value"); +>new Error("Unexpected value") : Error +>Error : ErrorConstructor +>"Unexpected value" : "Unexpected value" +} + +function f10(x: YesNo) { +>f10 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } +} + +function f11(x: YesNo) { +>f11 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} + +function f12(x: UnknownYesNo) { +>f12 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x) { +>x : Choice + + x; +>x : YesNo + } + else { + x; +>x : Choice + } +} + +function f13(x: UnknownYesNo) { +>f13 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x === Choice.Yes) { +>x === Choice.Yes : boolean +>x : Choice +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + x; +>x : Choice.Yes + } + else { + x; +>x : Choice.Unknown | Choice.No + } +} + +type Item = +>Item : Item + + { kind: Choice.Yes, a: string } | +>kind : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>a : string + + { kind: Choice.No, b: string }; +>kind : Choice.No +>Choice : any +>No : Choice.No +>b : string + +function f20(x: Item) { +>f20 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } +} + +function f21(x: Item) { +>f21 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes2.js b/tests/baselines/reference/stringEnumLiteralTypes2.js new file mode 100644 index 00000000000..07a5de7a85d --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes2.js @@ -0,0 +1,178 @@ +//// [stringEnumLiteralTypes2.ts] +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} + +//// [stringEnumLiteralTypes2.js] +; +function f1() { + var a; + var a; + var a; + var a; +} +function f2(a, b, c) { + b = a; + c = a; + c = b; +} +function f3(a, b) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} +function f5(a, b, c) { + var z1 = g("yes" /* Yes */); + var z2 = g("no" /* No */); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} +function assertNever(x) { + throw new Error("Unexpected value"); +} +function f10(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } +} +function f11(x) { + switch (x) { + case "yes" /* Yes */: return "true"; + case "no" /* No */: return "false"; + } + return assertNever(x); +} +function f12(x) { + if (x) { + x; + } + else { + x; + } +} +function f13(x) { + if (x === "yes" /* Yes */) { + x; + } + else { + x; + } +} +function f20(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } +} +function f21(x) { + switch (x.kind) { + case "yes" /* Yes */: return x.a; + case "no" /* No */: return x.b; + } + return assertNever(x); +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes2.symbols b/tests/baselines/reference/stringEnumLiteralTypes2.symbols new file mode 100644 index 00000000000..f746c0430cb --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes2.symbols @@ -0,0 +1,353 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes2.ts, 0, 19)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +type YesNo = Choice.Yes | Choice.No; +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +type NoYes = Choice.No | Choice.Yes; +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes2.ts, 2, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Unknown : Symbol(Choice.Unknown, Decl(stringEnumLiteralTypes2.ts, 0, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +function f1() { +>f1 : Symbol(f1, Decl(stringEnumLiteralTypes2.ts, 4, 60)) + + var a: YesNo; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + var a: NoYes; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>NoYes : Symbol(NoYes, Decl(stringEnumLiteralTypes2.ts, 2, 36)) + + var a: Choice.Yes | Choice.No; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + + var a: Choice.No | Choice.Yes; +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 7, 7), Decl(stringEnumLiteralTypes2.ts, 8, 7), Decl(stringEnumLiteralTypes2.ts, 9, 7), Decl(stringEnumLiteralTypes2.ts, 10, 7)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : Symbol(f2, Decl(stringEnumLiteralTypes2.ts, 11, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 13, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 13, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 13, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) + + b = a; +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 13, 21)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 13, 12)) + + c = a; +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 13, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 13, 12)) + + c = b; +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 13, 38)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 13, 21)) +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : Symbol(f3, Decl(stringEnumLiteralTypes2.ts, 17, 1)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + var x = a + b; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 20, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a == b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a != b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a === b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a !== b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a > b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a < b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a >= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = a <= b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) + + var y = !b; +>y : Symbol(y, Decl(stringEnumLiteralTypes2.ts, 21, 7), Decl(stringEnumLiteralTypes2.ts, 22, 7), Decl(stringEnumLiteralTypes2.ts, 23, 7), Decl(stringEnumLiteralTypes2.ts, 24, 7), Decl(stringEnumLiteralTypes2.ts, 25, 7), Decl(stringEnumLiteralTypes2.ts, 26, 7), Decl(stringEnumLiteralTypes2.ts, 27, 7), Decl(stringEnumLiteralTypes2.ts, 28, 7), Decl(stringEnumLiteralTypes2.ts, 29, 7)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 19, 26)) +} + +declare function g(x: Choice.Yes): string; +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 32, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + +declare function g(x: Choice.No): boolean; +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 33, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + +declare function g(x: Choice): number; +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 34, 19)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : Symbol(f5, Decl(stringEnumLiteralTypes2.ts, 34, 38)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 36, 12)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 36, 21)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 36, 38)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) + + var z1 = g(Choice.Yes); +>z1 : Symbol(z1, Decl(stringEnumLiteralTypes2.ts, 37, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + var z2 = g(Choice.No); +>z2 : Symbol(z2, Decl(stringEnumLiteralTypes2.ts, 38, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + + var z3 = g(a); +>z3 : Symbol(z3, Decl(stringEnumLiteralTypes2.ts, 39, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 36, 12)) + + var z4 = g(b); +>z4 : Symbol(z4, Decl(stringEnumLiteralTypes2.ts, 40, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 36, 21)) + + var z5 = g(c); +>z5 : Symbol(z5, Decl(stringEnumLiteralTypes2.ts, 41, 7)) +>g : Symbol(g, Decl(stringEnumLiteralTypes2.ts, 30, 1), Decl(stringEnumLiteralTypes2.ts, 32, 42), Decl(stringEnumLiteralTypes2.ts, 33, 42)) +>c : Symbol(c, Decl(stringEnumLiteralTypes2.ts, 36, 38)) +} + +function assertNever(x: never): never { +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes2.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 44, 21)) + + throw new Error("Unexpected value"); +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +} + +function f10(x: YesNo) { +>f10 : Symbol(f10, Decl(stringEnumLiteralTypes2.ts, 46, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 48, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 48, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + } +} + +function f11(x: YesNo) { +>f11 : Symbol(f11, Decl(stringEnumLiteralTypes2.ts, 53, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 55, 13)) +>YesNo : Symbol(YesNo, Decl(stringEnumLiteralTypes2.ts, 0, 59)) + + switch (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 55, 13)) + + case Choice.Yes: return "true"; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + case Choice.No: return "false"; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes2.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 55, 13)) +} + +function f12(x: UnknownYesNo) { +>f12 : Symbol(f12, Decl(stringEnumLiteralTypes2.ts, 61, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) + + if (x) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 63, 13)) + } +} + +function f13(x: UnknownYesNo) { +>f13 : Symbol(f13, Decl(stringEnumLiteralTypes2.ts, 70, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) +>UnknownYesNo : Symbol(UnknownYesNo, Decl(stringEnumLiteralTypes2.ts, 3, 36)) + + if (x === Choice.Yes) { +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) + + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) + } + else { + x; +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 72, 13)) + } +} + +type Item = +>Item : Symbol(Item, Decl(stringEnumLiteralTypes2.ts, 79, 1)) + + { kind: Choice.Yes, a: string } | +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) + + { kind: Choice.No, b: string }; +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 83, 5)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) + +function f20(x: Item) { +>f20 : Symbol(f20, Decl(stringEnumLiteralTypes2.ts, 83, 35)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes2.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 85, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) + } +} + +function f21(x: Item) { +>f21 : Symbol(f21, Decl(stringEnumLiteralTypes2.ts, 90, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>Item : Symbol(Item, Decl(stringEnumLiteralTypes2.ts, 79, 1)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>kind : Symbol(kind, Decl(stringEnumLiteralTypes2.ts, 82, 5), Decl(stringEnumLiteralTypes2.ts, 83, 5)) + + case Choice.Yes: return x.a; +>Choice.Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>Yes : Symbol(Choice.Yes, Decl(stringEnumLiteralTypes2.ts, 0, 33)) +>x.a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>a : Symbol(a, Decl(stringEnumLiteralTypes2.ts, 82, 23)) + + case Choice.No: return x.b; +>Choice.No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>Choice : Symbol(Choice, Decl(stringEnumLiteralTypes2.ts, 0, 0)) +>No : Symbol(Choice.No, Decl(stringEnumLiteralTypes2.ts, 0, 46)) +>x.b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +>b : Symbol(b, Decl(stringEnumLiteralTypes2.ts, 83, 22)) + } + return assertNever(x); +>assertNever : Symbol(assertNever, Decl(stringEnumLiteralTypes2.ts, 42, 1)) +>x : Symbol(x, Decl(stringEnumLiteralTypes2.ts, 92, 13)) +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes2.types b/tests/baselines/reference/stringEnumLiteralTypes2.types new file mode 100644 index 00000000000..7e4a51d9aea --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes2.types @@ -0,0 +1,383 @@ +=== tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts === +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; +>Choice : Choice +>Unknown : Choice.Unknown +>"" : "" +>Yes : Choice.Yes +>"yes" : "yes" +>No : Choice.No +>"no" : "no" + +type YesNo = Choice.Yes | Choice.No; +>YesNo : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +type NoYes = Choice.No | Choice.Yes; +>NoYes : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes + +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; +>UnknownYesNo : Choice +>Choice : any +>Unknown : Choice.Unknown +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + +function f1() { +>f1 : () => void + + var a: YesNo; +>a : YesNo +>YesNo : YesNo + + var a: NoYes; +>a : YesNo +>NoYes : YesNo + + var a: Choice.Yes | Choice.No; +>a : YesNo +>Choice : any +>Yes : Choice.Yes +>Choice : any +>No : Choice.No + + var a: Choice.No | Choice.Yes; +>a : YesNo +>Choice : any +>No : Choice.No +>Choice : any +>Yes : Choice.Yes +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { +>f2 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + b = a; +>b = a : YesNo +>b : Choice +>a : YesNo + + c = a; +>c = a : YesNo +>c : Choice +>a : YesNo + + c = b; +>c = b : YesNo +>c : Choice +>b : YesNo +} + +function f3(a: Choice.Yes, b: YesNo) { +>f3 : (a: Choice.Yes, b: YesNo) => void +>a : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>b : YesNo +>YesNo : YesNo + + var x = a + b; +>x : string +>a + b : string +>a : Choice.Yes +>b : YesNo + + var y = a == b; +>y : boolean +>a == b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a != b; +>y : boolean +>a != b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a === b; +>y : boolean +>a === b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a !== b; +>y : boolean +>a !== b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a > b; +>y : boolean +>a > b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a < b; +>y : boolean +>a < b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a >= b; +>y : boolean +>a >= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = a <= b; +>y : boolean +>a <= b : boolean +>a : Choice.Yes +>b : YesNo + + var y = !b; +>y : boolean +>!b : false +>b : YesNo +} + +declare function g(x: Choice.Yes): string; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.Yes +>Choice : any +>Yes : Choice.Yes + +declare function g(x: Choice.No): boolean; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice.No +>Choice : any +>No : Choice.No + +declare function g(x: Choice): number; +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>x : Choice +>Choice : Choice + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { +>f5 : (a: YesNo, b: Choice, c: Choice) => void +>a : YesNo +>YesNo : YesNo +>b : Choice +>UnknownYesNo : Choice +>c : Choice +>Choice : Choice + + var z1 = g(Choice.Yes); +>z1 : string +>g(Choice.Yes) : string +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + var z2 = g(Choice.No); +>z2 : boolean +>g(Choice.No) : boolean +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No + + var z3 = g(a); +>z3 : number +>g(a) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>a : YesNo + + var z4 = g(b); +>z4 : number +>g(b) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>b : Choice + + var z5 = g(c); +>z5 : number +>g(c) : number +>g : { (x: Choice.Yes): string; (x: Choice.No): boolean; (x: Choice): number; } +>c : Choice +} + +function assertNever(x: never): never { +>assertNever : (x: never) => never +>x : never + + throw new Error("Unexpected value"); +>new Error("Unexpected value") : Error +>Error : ErrorConstructor +>"Unexpected value" : "Unexpected value" +} + +function f10(x: YesNo) { +>f10 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } +} + +function f11(x: YesNo) { +>f11 : (x: YesNo) => "true" | "false" +>x : YesNo +>YesNo : YesNo + + switch (x) { +>x : YesNo + + case Choice.Yes: return "true"; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>"true" : "true" + + case Choice.No: return "false"; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>"false" : "false" + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} + +function f12(x: UnknownYesNo) { +>f12 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x) { +>x : Choice + + x; +>x : YesNo + } + else { + x; +>x : Choice.Unknown + } +} + +function f13(x: UnknownYesNo) { +>f13 : (x: Choice) => void +>x : Choice +>UnknownYesNo : Choice + + if (x === Choice.Yes) { +>x === Choice.Yes : boolean +>x : Choice +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes + + x; +>x : Choice.Yes + } + else { + x; +>x : Choice.Unknown | Choice.No + } +} + +type Item = +>Item : Item + + { kind: Choice.Yes, a: string } | +>kind : Choice.Yes +>Choice : any +>Yes : Choice.Yes +>a : string + + { kind: Choice.No, b: string }; +>kind : Choice.No +>Choice : any +>No : Choice.No +>b : string + +function f20(x: Item) { +>f20 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } +} + +function f21(x: Item) { +>f21 : (x: Item) => string +>x : Item +>Item : Item + + switch (x.kind) { +>x.kind : YesNo +>x : Item +>kind : YesNo + + case Choice.Yes: return x.a; +>Choice.Yes : Choice.Yes +>Choice : typeof Choice +>Yes : Choice.Yes +>x.a : string +>x : { kind: Choice.Yes; a: string; } +>a : string + + case Choice.No: return x.b; +>Choice.No : Choice.No +>Choice : typeof Choice +>No : Choice.No +>x.b : string +>x : { kind: Choice.No; b: string; } +>b : string + } + return assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} diff --git a/tests/baselines/reference/stringEnumLiteralTypes3.errors.txt b/tests/baselines/reference/stringEnumLiteralTypes3.errors.txt new file mode 100644 index 00000000000..7feed87d824 --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes3.errors.txt @@ -0,0 +1,166 @@ +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(10,5): error TS2322: Type 'YesNo' is not assignable to type 'Choice.Yes'. + Type 'Choice.No' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(11,5): error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(12,5): error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(18,5): error TS2322: Type 'Choice' is not assignable to type 'YesNo'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(19,5): error TS2322: Type 'Choice' is not assignable to type 'YesNo'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(37,5): error TS2322: Type 'Choice.Unknown' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(39,5): error TS2322: Type 'Choice.No' is not assignable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(40,5): error TS2322: Type 'Choice.Unknown' is not assignable to type 'YesNo'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(52,5): error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.Unknown'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(54,5): error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.No'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(55,5): error TS2365: Operator '===' cannot be applied to types 'YesNo' and 'Choice.Unknown'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(87,14): error TS2678: Type 'Choice.Unknown' is not comparable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(89,14): error TS2678: Type 'Choice.No' is not comparable to type 'Choice.Yes'. +tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts(96,14): error TS2678: Type 'Choice.Unknown' is not comparable to type 'YesNo'. + + +==== tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts (14 errors) ==== + const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + + type Yes = Choice.Yes; + type YesNo = Choice.Yes | Choice.No; + type NoYes = Choice.No | Choice.Yes; + type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + + function f1(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = a; + a = b; + ~ +!!! error TS2322: Type 'YesNo' is not assignable to type 'Choice.Yes'. +!!! error TS2322: Type 'Choice.No' is not assignable to type 'Choice.Yes'. + a = c; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. + a = d; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'Choice.Yes'. + } + + function f2(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + b = a; + b = b; + b = c; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'YesNo'. + b = d; + ~ +!!! error TS2322: Type 'Choice' is not assignable to type 'YesNo'. + } + + function f3(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + c = a; + c = b; + c = c; + c = d; + } + + function f4(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + d = a; + d = b; + d = c; + d = d; + } + + function f5(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = Choice.Unknown; + ~ +!!! error TS2322: Type 'Choice.Unknown' is not assignable to type 'Choice.Yes'. + a = Choice.Yes; + a = Choice.No; + ~ +!!! error TS2322: Type 'Choice.No' is not assignable to type 'Choice.Yes'. + b = Choice.Unknown; + ~ +!!! error TS2322: Type 'Choice.Unknown' is not assignable to type 'YesNo'. + b = Choice.Yes; + b = Choice.No; + c = Choice.Unknown; + c = Choice.Yes; + c = Choice.No; + d = Choice.Unknown; + d = Choice.Yes; + d = Choice.No; + } + + function f6(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === Choice.Unknown; + ~~~~~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.Unknown'. + a === Choice.Yes; + a === Choice.No; + ~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '===' cannot be applied to types 'Choice.Yes' and 'Choice.No'. + b === Choice.Unknown; + ~~~~~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '===' cannot be applied to types 'YesNo' and 'Choice.Unknown'. + b === Choice.Yes; + b === Choice.No; + c === Choice.Unknown; + c === Choice.Yes; + c === Choice.No; + d === Choice.Unknown; + d === Choice.Yes; + d === Choice.No; + } + + function f7(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; + } + + function f10(x: Yes): Yes { + switch (x) { + case Choice.Unknown: return x; + ~~~~~~~~~~~~~~ +!!! error TS2678: Type 'Choice.Unknown' is not comparable to type 'Choice.Yes'. + case Choice.Yes: return x; + case Choice.No: return x; + ~~~~~~~~~ +!!! error TS2678: Type 'Choice.No' is not comparable to type 'Choice.Yes'. + } + return x; + } + + function f11(x: YesNo): YesNo { + switch (x) { + case Choice.Unknown: return x; + ~~~~~~~~~~~~~~ +!!! error TS2678: Type 'Choice.Unknown' is not comparable to type 'YesNo'. + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; + } + + function f12(x: UnknownYesNo): UnknownYesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; + } + + function f13(x: Choice): Choice { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; + } \ No newline at end of file diff --git a/tests/baselines/reference/stringEnumLiteralTypes3.js b/tests/baselines/reference/stringEnumLiteralTypes3.js new file mode 100644 index 00000000000..7e2699460b2 --- /dev/null +++ b/tests/baselines/reference/stringEnumLiteralTypes3.js @@ -0,0 +1,225 @@ +//// [stringEnumLiteralTypes3.ts] +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type Yes = Choice.Yes; +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = a; + a = b; + a = c; + a = d; +} + +function f2(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + b = a; + b = b; + b = c; + b = d; +} + +function f3(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + c = a; + c = b; + c = c; + c = d; +} + +function f4(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + d = a; + d = b; + d = c; + d = d; +} + +function f5(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = Choice.Unknown; + a = Choice.Yes; + a = Choice.No; + b = Choice.Unknown; + b = Choice.Yes; + b = Choice.No; + c = Choice.Unknown; + c = Choice.Yes; + c = Choice.No; + d = Choice.Unknown; + d = Choice.Yes; + d = Choice.No; +} + +function f6(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === Choice.Unknown; + a === Choice.Yes; + a === Choice.No; + b === Choice.Unknown; + b === Choice.Yes; + b === Choice.No; + c === Choice.Unknown; + c === Choice.Yes; + c === Choice.No; + d === Choice.Unknown; + d === Choice.Yes; + d === Choice.No; +} + +function f7(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; +} + +function f10(x: Yes): Yes { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f11(x: YesNo): YesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f12(x: UnknownYesNo): UnknownYesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f13(x: Choice): Choice { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +//// [stringEnumLiteralTypes3.js] +; +function f1(a, b, c, d) { + a = a; + a = b; + a = c; + a = d; +} +function f2(a, b, c, d) { + b = a; + b = b; + b = c; + b = d; +} +function f3(a, b, c, d) { + c = a; + c = b; + c = c; + c = d; +} +function f4(a, b, c, d) { + d = a; + d = b; + d = c; + d = d; +} +function f5(a, b, c, d) { + a = "" /* Unknown */; + a = "yes" /* Yes */; + a = "no" /* No */; + b = "" /* Unknown */; + b = "yes" /* Yes */; + b = "no" /* No */; + c = "" /* Unknown */; + c = "yes" /* Yes */; + c = "no" /* No */; + d = "" /* Unknown */; + d = "yes" /* Yes */; + d = "no" /* No */; +} +function f6(a, b, c, d) { + a === "" /* Unknown */; + a === "yes" /* Yes */; + a === "no" /* No */; + b === "" /* Unknown */; + b === "yes" /* Yes */; + b === "no" /* No */; + c === "" /* Unknown */; + c === "yes" /* Yes */; + c === "no" /* No */; + d === "" /* Unknown */; + d === "yes" /* Yes */; + d === "no" /* No */; +} +function f7(a, b, c, d) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; +} +function f10(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} +function f11(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} +function f12(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} +function f13(x) { + switch (x) { + case "" /* Unknown */: return x; + case "yes" /* Yes */: return x; + case "no" /* No */: return x; + } + return x; +} diff --git a/tests/cases/conformance/enums/enumClassification.ts b/tests/cases/conformance/enums/enumClassification.ts new file mode 100644 index 00000000000..bbb05984088 --- /dev/null +++ b/tests/cases/conformance/enums/enumClassification.ts @@ -0,0 +1,80 @@ +// @declaration: true + +// An enum type where each member has no initializer or an initializer that specififes +// a numeric literal, a string literal, or a single identifier naming another member in +// the enum type is classified as a literal enum type. An enum type that doesn't adhere +// to this pattern is classified as a numeric enum type. + +// Examples of literal enum types + +enum E01 { + A +} + +enum E02 { + A = 123 +} + +enum E03 { + A = "hello" +} + +enum E04 { + A, + B, + C +} + +enum E05 { + A, + B = 10, + C +} + +enum E06 { + A = "one", + B = "two", + C = "three" +} + +enum E07 { + A, + B, + C = "hi", + D = 10, + E, + F = "bye" +} + +enum E08 { + A = 10, + B = "hello", + C = A, + D = B, + E = C, +} + +// Examples of numeric enum types with only constant members + +enum E10 {} + +enum E11 { + A = +0, + B, + C +} + +enum E12 { + A = 1 << 0, + B = 1 << 1, + C = 1 << 2 +} + +// Examples of numeric enum types with constant and computed members + +enum E20 { + A = "foo".length, + B = A + 1, + C = +"123", + D = Math.sin(1) +} diff --git a/tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts b/tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts new file mode 100644 index 00000000000..11be7c90603 --- /dev/null +++ b/tests/cases/conformance/types/literal/stringEnumLiteralTypes1.ts @@ -0,0 +1,99 @@ +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} \ No newline at end of file diff --git a/tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts b/tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts new file mode 100644 index 00000000000..f6a71fcaa74 --- /dev/null +++ b/tests/cases/conformance/types/literal/stringEnumLiteralTypes2.ts @@ -0,0 +1,101 @@ +// @strictNullChecks: true + +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1() { + var a: YesNo; + var a: NoYes; + var a: Choice.Yes | Choice.No; + var a: Choice.No | Choice.Yes; +} + +function f2(a: YesNo, b: UnknownYesNo, c: Choice) { + b = a; + c = a; + c = b; +} + +function f3(a: Choice.Yes, b: YesNo) { + var x = a + b; + var y = a == b; + var y = a != b; + var y = a === b; + var y = a !== b; + var y = a > b; + var y = a < b; + var y = a >= b; + var y = a <= b; + var y = !b; +} + +declare function g(x: Choice.Yes): string; +declare function g(x: Choice.No): boolean; +declare function g(x: Choice): number; + +function f5(a: YesNo, b: UnknownYesNo, c: Choice) { + var z1 = g(Choice.Yes); + var z2 = g(Choice.No); + var z3 = g(a); + var z4 = g(b); + var z5 = g(c); +} + +function assertNever(x: never): never { + throw new Error("Unexpected value"); +} + +function f10(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } +} + +function f11(x: YesNo) { + switch (x) { + case Choice.Yes: return "true"; + case Choice.No: return "false"; + } + return assertNever(x); +} + +function f12(x: UnknownYesNo) { + if (x) { + x; + } + else { + x; + } +} + +function f13(x: UnknownYesNo) { + if (x === Choice.Yes) { + x; + } + else { + x; + } +} + +type Item = + { kind: Choice.Yes, a: string } | + { kind: Choice.No, b: string }; + +function f20(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } +} + +function f21(x: Item) { + switch (x.kind) { + case Choice.Yes: return x.a; + case Choice.No: return x.b; + } + return assertNever(x); +} \ No newline at end of file diff --git a/tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts b/tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts new file mode 100644 index 00000000000..f296fd875f6 --- /dev/null +++ b/tests/cases/conformance/types/literal/stringEnumLiteralTypes3.ts @@ -0,0 +1,119 @@ +const enum Choice { Unknown = "", Yes = "yes", No = "no" }; + +type Yes = Choice.Yes; +type YesNo = Choice.Yes | Choice.No; +type NoYes = Choice.No | Choice.Yes; +type UnknownYesNo = Choice.Unknown | Choice.Yes | Choice.No; + +function f1(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = a; + a = b; + a = c; + a = d; +} + +function f2(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + b = a; + b = b; + b = c; + b = d; +} + +function f3(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + c = a; + c = b; + c = c; + c = d; +} + +function f4(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + d = a; + d = b; + d = c; + d = d; +} + +function f5(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a = Choice.Unknown; + a = Choice.Yes; + a = Choice.No; + b = Choice.Unknown; + b = Choice.Yes; + b = Choice.No; + c = Choice.Unknown; + c = Choice.Yes; + c = Choice.No; + d = Choice.Unknown; + d = Choice.Yes; + d = Choice.No; +} + +function f6(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === Choice.Unknown; + a === Choice.Yes; + a === Choice.No; + b === Choice.Unknown; + b === Choice.Yes; + b === Choice.No; + c === Choice.Unknown; + c === Choice.Yes; + c === Choice.No; + d === Choice.Unknown; + d === Choice.Yes; + d === Choice.No; +} + +function f7(a: Yes, b: YesNo, c: UnknownYesNo, d: Choice) { + a === a; + a === b; + a === c; + a === d; + b === a; + b === b; + b === c; + b === d; + c === a; + c === b; + c === c; + c === d; + d === a; + d === b; + d === c; + d === d; +} + +function f10(x: Yes): Yes { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f11(x: YesNo): YesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f12(x: UnknownYesNo): UnknownYesNo { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} + +function f13(x: Choice): Choice { + switch (x) { + case Choice.Unknown: return x; + case Choice.Yes: return x; + case Choice.No: return x; + } + return x; +} \ No newline at end of file From 640e8f5255844b3a29597b0631ce083dbc31b953 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 1 May 2017 07:12:27 -0700 Subject: [PATCH 029/282] Fix declaration emit for string valued enum members --- src/compiler/declarationEmitter.ts | 2 +- src/compiler/utilities.ts | 6 +++++- src/services/symbolDisplay.ts | 6 ++---- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 2bd8d5971fb..495713ac07a 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -985,7 +985,7 @@ namespace ts { const enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 8080f6985e8..624136b26a6 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -349,7 +349,11 @@ namespace ts { Debug.fail(`Literal kind '${node.kind}' not accounted for.`); } - export function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) { + export function getTextOfConstantValue(value: string | number) { + return typeof value === "string" ? getQuotedEscapedLiteralText('"', value, '"') : "" + value; + } + + function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) { return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 8f61ca9c914..43eb07b343b 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -330,10 +330,8 @@ namespace ts.SymbolDisplay { displayParts.push(spacePart()); displayParts.push(operatorPart(SyntaxKind.EqualsToken)); displayParts.push(spacePart()); - const valuePart = typeof constantValue === "number" ? - displayPart("" + constantValue, SymbolDisplayPartKind.numericLiteral) : - displayPart(getQuotedEscapedLiteralText('"', constantValue, '"'), SymbolDisplayPartKind.stringLiteral); - displayParts.push(valuePart); + displayParts.push(displayPart(getTextOfConstantValue(constantValue), + typeof constantValue === "number" ? SymbolDisplayPartKind.numericLiteral : SymbolDisplayPartKind.stringLiteral)); } } } From 25a01c04235cb6d33225b3dda2a5d604cfb0fae6 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 1 May 2017 07:12:38 -0700 Subject: [PATCH 030/282] Accept new baselines --- .../baselines/reference/enumClassification.js | 106 ++---------------- 1 file changed, 8 insertions(+), 98 deletions(-) diff --git a/tests/baselines/reference/enumClassification.js b/tests/baselines/reference/enumClassification.js index f1532300027..0a046dc60d2 100644 --- a/tests/baselines/reference/enumClassification.js +++ b/tests/baselines/reference/enumClassification.js @@ -166,7 +166,7 @@ declare enum E02 { A = 123, } declare enum E03 { - A = hello, + A = "hello", } declare enum E04 { A = 0, @@ -179,23 +179,23 @@ declare enum E05 { C = 11, } declare enum E06 { - A = one, - B = two, - C = three, + A = "one", + B = "two", + C = "three", } declare enum E07 { A = 0, B = 1, - C = hi, + C = "hi", D = 10, E = 11, - F = bye, + F = "bye", } declare enum E08 { A = 10, - B = hello, + B = "hello", C = 10, - D = hello, + D = "hello", E = 10, } declare enum E10 { @@ -216,93 +216,3 @@ declare enum E20 { C, D, } - - -//// [DtsFileErrors] - - -tests/cases/conformance/enums/enumClassification.d.ts(8,9): error TS1066: In ambient enum declarations member initializer must be constant expression. -tests/cases/conformance/enums/enumClassification.d.ts(21,9): error TS1066: In ambient enum declarations member initializer must be constant expression. -tests/cases/conformance/enums/enumClassification.d.ts(22,9): error TS1066: In ambient enum declarations member initializer must be constant expression. -tests/cases/conformance/enums/enumClassification.d.ts(23,9): error TS1066: In ambient enum declarations member initializer must be constant expression. -tests/cases/conformance/enums/enumClassification.d.ts(28,9): error TS1066: In ambient enum declarations member initializer must be constant expression. -tests/cases/conformance/enums/enumClassification.d.ts(31,9): error TS1066: In ambient enum declarations member initializer must be constant expression. -tests/cases/conformance/enums/enumClassification.d.ts(35,9): error TS1066: In ambient enum declarations member initializer must be constant expression. -tests/cases/conformance/enums/enumClassification.d.ts(37,9): error TS1066: In ambient enum declarations member initializer must be constant expression. - - -==== tests/cases/conformance/enums/enumClassification.d.ts (8 errors) ==== - declare enum E01 { - A = 0, - } - declare enum E02 { - A = 123, - } - declare enum E03 { - A = hello, - ~~~~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - } - declare enum E04 { - A = 0, - B = 1, - C = 2, - } - declare enum E05 { - A = 0, - B = 10, - C = 11, - } - declare enum E06 { - A = one, - ~~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - B = two, - ~~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - C = three, - ~~~~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - } - declare enum E07 { - A = 0, - B = 1, - C = hi, - ~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - D = 10, - E = 11, - F = bye, - ~~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - } - declare enum E08 { - A = 10, - B = hello, - ~~~~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - C = 10, - D = hello, - ~~~~~ -!!! error TS1066: In ambient enum declarations member initializer must be constant expression. - E = 10, - } - declare enum E10 { - } - declare enum E11 { - A = 0, - B = 1, - C = 2, - } - declare enum E12 { - A = 1, - B = 2, - C = 4, - } - declare enum E20 { - A, - B, - C, - D, - } - \ No newline at end of file From ceb78f9607832b321dbd9bb9d2c086a65db5aa15 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 1 May 2017 09:10:51 -0700 Subject: [PATCH 031/282] A couple of small simplifications --- src/compiler/checker.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c88951d8f21..ee46e78774a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3051,7 +3051,7 @@ namespace ts { buildSymbolDisplay(parent, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); // In a literal enum type with a single member E { A }, E and E.A denote the // same type. We always display this type simply as E. - if (getDeclaredTypeOfSymbol(parent).flags & TypeFlags.Union) { + if (getDeclaredTypeOfSymbol(parent) !== type) { writePunctuation(writer, SyntaxKind.DotToken); appendSymbolNameOnly(type.symbol, writer); } @@ -4958,9 +4958,7 @@ namespace ts { for (const member of (declaration).members) { const memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - if (!contains(memberTypeList, memberType)) { - memberTypeList.push(memberType); - } + memberTypeList.push(memberType); } } } From c1d851c7ec4b0ce09e06f7982642f115a89631c2 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Tue, 2 May 2017 02:06:23 +0900 Subject: [PATCH 032/282] allow use of arguments on ambient context --- src/compiler/binder.ts | 39 +++++++++---- ...lisionArgumentsClassConstructor.errors.txt | 29 +--------- .../collisionArgumentsClassMethod.errors.txt | 29 +--------- .../collisionArgumentsFunction.errors.txt | 15 +++-- .../reference/collisionArgumentsFunction.js | 19 +++++-- .../reference/collisionArgumentsInType.js | 2 + .../collisionArgumentsInType.symbols | 57 ++++++++++--------- .../reference/collisionArgumentsInType.types | 3 + .../collisionArgumentsInterfaceMembers.js | 2 + ...collisionArgumentsInterfaceMembers.symbols | 51 +++++++++-------- .../collisionArgumentsInterfaceMembers.types | 3 + .../compiler/collisionArgumentsFunction.ts | 15 +++-- .../compiler/collisionArgumentsInType.ts | 1 + .../collisionArgumentsInterfaceMembers.ts | 1 + 14 files changed, 129 insertions(+), 137 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 27b3067278c..759e56d449c 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -221,7 +221,7 @@ namespace ts { // other kinds of value declarations take precedence over modules symbol.valueDeclaration = node; } - } + } } // Should not be called on a declaration with a computed property name, @@ -389,9 +389,9 @@ namespace ts { // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(node).isExportEquals))) { - message = Diagnostics.A_module_cannot_have_multiple_default_exports; - } + (isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(node).isExportEquals))) { + message = Diagnostics.A_module_cannot_have_multiple_default_exports; + } } } @@ -1414,7 +1414,7 @@ namespace ts { if (isObjectLiteralOrClassExpressionMethod(node)) { return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod; } - // falls through + // falls through case SyntaxKind.Constructor: case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodSignature: @@ -1716,7 +1716,7 @@ namespace ts { declareModuleMember(node, symbolFlags, symbolExcludes); break; } - // falls through + // falls through default: if (!blockScopeContainer.locals) { blockScopeContainer.locals = createMap(); @@ -2010,7 +2010,7 @@ namespace ts { bindBlockScopedDeclaration(parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); break; } - // falls through + // falls through case SyntaxKind.ThisKeyword: if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) { node.flowNode = currentFlow; @@ -2186,7 +2186,7 @@ namespace ts { if (!isFunctionLike(node.parent)) { return; } - // falls through + // falls through case SyntaxKind.ModuleBlock: return updateStrictModeStatementList((node).statements); } @@ -2211,7 +2211,7 @@ namespace ts { } function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName) }"`); + bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`); } function bindExportAssignment(node: ExportAssignment | BinaryExpression) { @@ -2503,8 +2503,27 @@ namespace ts { } } + function needParameterStrictModeCheck(node: Node) { + if (node.parent.kind === SyntaxKind.ConstructorType || node.parent.kind === SyntaxKind.FunctionType) { + return false; + } + + if (node.parent.parent && ( + node.parent.parent.kind === SyntaxKind.InterfaceDeclaration || + node.parent.parent.kind === SyntaxKind.TypeLiteral + )) { + return false; + } + + if (isDeclarationFile(file) || isInAmbientContext(node)) { + return false; + } + + return true; + } + function bindParameter(node: ParameterDeclaration) { - if (inStrictMode) { + if (inStrictMode && needParameterStrictModeCheck(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); diff --git a/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt b/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt index 03bf4f9e38b..a7066fb1fbe 100644 --- a/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt +++ b/tests/baselines/reference/collisionArgumentsClassConstructor.errors.txt @@ -13,9 +13,6 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(30,24): error TS1210: tests/cases/compiler/collisionArgumentsClassConstructor.ts(31,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(35,24): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(36,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(41,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(44,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(47,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(51,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(52,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(53,25): error TS2396: Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters. @@ -30,15 +27,9 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(67,17): error TS1210: tests/cases/compiler/collisionArgumentsClassConstructor.ts(68,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(69,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassConstructor.ts(70,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(75,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(76,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(79,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(80,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(84,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -==== tests/cases/compiler/collisionArgumentsClassConstructor.ts (38 errors) ==== +==== tests/cases/compiler/collisionArgumentsClassConstructor.ts (29 errors) ==== // Constructors class c1 { constructor(i: number, ...arguments) { // error @@ -110,18 +101,12 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210: declare class c4 { constructor(i: number, ...arguments); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c42 { constructor(arguments: number, ...rest); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c4NoError { constructor(arguments: number); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } class c5 { @@ -178,26 +163,14 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210: declare class c6 { constructor(i: number, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. constructor(i: string, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c62 { constructor(arguments: number, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. constructor(arguments: string, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } declare class c6NoError { constructor(arguments: number); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. constructor(arguments: string); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } \ No newline at end of file diff --git a/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt b/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt index ea699414f17..ec0562f57ca 100644 --- a/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt +++ b/tests/baselines/reference/collisionArgumentsClassMethod.errors.txt @@ -20,20 +20,11 @@ tests/cases/compiler/collisionArgumentsClassMethod.ts(21,22): error TS1210: Inva tests/cases/compiler/collisionArgumentsClassMethod.ts(22,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(23,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(24,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(29,30): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(30,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(31,23): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(33,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(34,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(35,16): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(36,16): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(37,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -tests/cases/compiler/collisionArgumentsClassMethod.ts(38,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(43,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/compiler/collisionArgumentsClassMethod.ts(46,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. -==== tests/cases/compiler/collisionArgumentsClassMethod.ts (33 errors) ==== +==== tests/cases/compiler/collisionArgumentsClassMethod.ts (24 errors) ==== class c1 { public foo(i: number, ...arguments) { //arguments is error ~~~~~~~~~~~~ @@ -107,33 +98,15 @@ tests/cases/compiler/collisionArgumentsClassMethod.ts(46,13): error TS1210: Inva declare class c2 { public foo(i: number, ...arguments); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public foo1(arguments: number, ...rest); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public fooNoError(arguments: number); // No error - no code gen - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4(i: number, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4(i: string, ...arguments); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f41(arguments: number, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f41(arguments: string, ...rest); // no codegen no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4NoError(arguments: number); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. public f4NoError(arguments: string); // no error - ~~~~~~~~~ -!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. } class c3 { diff --git a/tests/baselines/reference/collisionArgumentsFunction.errors.txt b/tests/baselines/reference/collisionArgumentsFunction.errors.txt index a557e9cbcba..f5388af6a14 100644 --- a/tests/baselines/reference/collisionArgumentsFunction.errors.txt +++ b/tests/baselines/reference/collisionArgumentsFunction.errors.txt @@ -51,9 +51,12 @@ tests/cases/compiler/collisionArgumentsFunction.ts(30,22): error TS2396: Duplica var arguments: any; // No error } - declare function f5(arguments: number, ...rest); // no codegen no error - declare function f5(arguments: string, ...rest); // no codegen no error - declare function f52(i: number, ...arguments); // no codegen no error - declare function f52(i: string, ...arguments); // no codegen no error - declare function f6(arguments: number); // no codegen no error - declare function f6(arguments: string); // no codegen no error \ No newline at end of file + namespace strict { + "use strict"; + declare function f5(arguments: number, ...rest); // no codegen no error + declare function f5(arguments: string, ...rest); // no codegen no error + declare function f52(i: number, ...arguments); // no codegen no error + declare function f52(i: string, ...arguments); // no codegen no error + declare function f6(arguments: number); // no codegen no error + declare function f6(arguments: string); // no codegen no error + } \ No newline at end of file diff --git a/tests/baselines/reference/collisionArgumentsFunction.js b/tests/baselines/reference/collisionArgumentsFunction.js index c6a26baa495..64cd2682a4a 100644 --- a/tests/baselines/reference/collisionArgumentsFunction.js +++ b/tests/baselines/reference/collisionArgumentsFunction.js @@ -37,12 +37,15 @@ function f4NoError(arguments: any) { // no error var arguments: any; // No error } -declare function f5(arguments: number, ...rest); // no codegen no error -declare function f5(arguments: string, ...rest); // no codegen no error -declare function f52(i: number, ...arguments); // no codegen no error -declare function f52(i: string, ...arguments); // no codegen no error -declare function f6(arguments: number); // no codegen no error -declare function f6(arguments: string); // no codegen no error +namespace strict { + "use strict"; + declare function f5(arguments: number, ...rest); // no codegen no error + declare function f5(arguments: string, ...rest); // no codegen no error + declare function f52(i: number, ...arguments); // no codegen no error + declare function f52(i: string, ...arguments); // no codegen no error + declare function f6(arguments: number); // no codegen no error + declare function f6(arguments: string); // no codegen no error +} //// [collisionArgumentsFunction.js] // Functions @@ -90,3 +93,7 @@ function f42(i) { function f4NoError(arguments) { var arguments; // No error } +var strict; +(function (strict) { + "use strict"; +})(strict || (strict = {})); diff --git a/tests/baselines/reference/collisionArgumentsInType.js b/tests/baselines/reference/collisionArgumentsInType.js index 4db7c930775..e9ff629f76e 100644 --- a/tests/baselines/reference/collisionArgumentsInType.js +++ b/tests/baselines/reference/collisionArgumentsInType.js @@ -1,4 +1,5 @@ //// [collisionArgumentsInType.ts] +"use strict"; var v1: (i: number, ...arguments) => void; // no error - no code gen var v12: (arguments: number, ...restParameters) => void; // no error - no code gen var v2: { @@ -15,6 +16,7 @@ var v21: { } //// [collisionArgumentsInType.js] +"use strict"; var v1; // no error - no code gen var v12; // no error - no code gen var v2; diff --git a/tests/baselines/reference/collisionArgumentsInType.symbols b/tests/baselines/reference/collisionArgumentsInType.symbols index 94c9374c7cd..d2ec9ce6705 100644 --- a/tests/baselines/reference/collisionArgumentsInType.symbols +++ b/tests/baselines/reference/collisionArgumentsInType.symbols @@ -1,53 +1,54 @@ === tests/cases/compiler/collisionArgumentsInType.ts === +"use strict"; var v1: (i: number, ...arguments) => void; // no error - no code gen ->v1 : Symbol(v1, Decl(collisionArgumentsInType.ts, 0, 3)) ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 0, 9)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 0, 19)) +>v1 : Symbol(v1, Decl(collisionArgumentsInType.ts, 1, 3)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 1, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 1, 19)) var v12: (arguments: number, ...restParameters) => void; // no error - no code gen ->v12 : Symbol(v12, Decl(collisionArgumentsInType.ts, 1, 3)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 1, 10)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 1, 28)) +>v12 : Symbol(v12, Decl(collisionArgumentsInType.ts, 2, 3)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 2, 10)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 2, 28)) var v2: { ->v2 : Symbol(v2, Decl(collisionArgumentsInType.ts, 2, 3)) +>v2 : Symbol(v2, Decl(collisionArgumentsInType.ts, 3, 3)) (arguments: number, ...restParameters); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 3, 5)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 3, 23)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 4, 5)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 4, 23)) new (arguments: number, ...restParameters); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 4, 9)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 4, 27)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 5, 9)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 5, 27)) foo(arguments: number, ...restParameters); // no error - no code gen ->foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 4, 47)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 5, 8)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 5, 26)) +>foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 5, 47)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 6, 8)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 6, 26)) prop: (arguments: number, ...restParameters) => void; // no error - no code gen ->prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 5, 46)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 6, 11)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 6, 29)) +>prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 6, 46)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 7, 11)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 7, 29)) } var v21: { ->v21 : Symbol(v21, Decl(collisionArgumentsInType.ts, 8, 3)) +>v21 : Symbol(v21, Decl(collisionArgumentsInType.ts, 9, 3)) (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 9, 5)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 9, 15)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 10, 5)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 10, 15)) new (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 10, 9)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 10, 19)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 11, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 11, 19)) foo(i: number, ...arguments); // no error - no code gen ->foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 10, 34)) ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 11, 8)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 11, 18)) +>foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 11, 34)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 12, 8)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 12, 18)) prop: (i: number, ...arguments) => void; // no error - no code gen ->prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 11, 33)) ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 12, 11)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 12, 21)) +>prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 12, 33)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 13, 11)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 13, 21)) } diff --git a/tests/baselines/reference/collisionArgumentsInType.types b/tests/baselines/reference/collisionArgumentsInType.types index a8096e2e7f5..7b4c8983b4c 100644 --- a/tests/baselines/reference/collisionArgumentsInType.types +++ b/tests/baselines/reference/collisionArgumentsInType.types @@ -1,4 +1,7 @@ === tests/cases/compiler/collisionArgumentsInType.ts === +"use strict"; +>"use strict" : "use strict" + var v1: (i: number, ...arguments) => void; // no error - no code gen >v1 : (i: number, ...arguments: any[]) => void >i : number diff --git a/tests/baselines/reference/collisionArgumentsInterfaceMembers.js b/tests/baselines/reference/collisionArgumentsInterfaceMembers.js index a55e112b603..34530ca2c72 100644 --- a/tests/baselines/reference/collisionArgumentsInterfaceMembers.js +++ b/tests/baselines/reference/collisionArgumentsInterfaceMembers.js @@ -1,4 +1,5 @@ //// [collisionArgumentsInterfaceMembers.ts] +"use strict"; // call interface i1 { (i: number, ...arguments); // no error - no code gen @@ -29,3 +30,4 @@ interface i3 { } //// [collisionArgumentsInterfaceMembers.js] +"use strict"; diff --git a/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols b/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols index f0a82bec521..a7e14b5959e 100644 --- a/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols +++ b/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols @@ -1,63 +1,64 @@ === tests/cases/compiler/collisionArgumentsInterfaceMembers.ts === +"use strict"; // call interface i1 { ->i1 : Symbol(i1, Decl(collisionArgumentsInterfaceMembers.ts, 0, 0)) +>i1 : Symbol(i1, Decl(collisionArgumentsInterfaceMembers.ts, 0, 13)) (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 2, 5)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 2, 15)) +>i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 3, 5)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 3, 15)) } interface i12 { ->i12 : Symbol(i12, Decl(collisionArgumentsInterfaceMembers.ts, 3, 1)) +>i12 : Symbol(i12, Decl(collisionArgumentsInterfaceMembers.ts, 4, 1)) (arguments: number, ...rest); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 5, 5)) ->rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 5, 23)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 6, 5)) +>rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 6, 23)) } interface i1NoError { ->i1NoError : Symbol(i1NoError, Decl(collisionArgumentsInterfaceMembers.ts, 6, 1)) +>i1NoError : Symbol(i1NoError, Decl(collisionArgumentsInterfaceMembers.ts, 7, 1)) (arguments: number); // no error ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 8, 5)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 9, 5)) } // new interface i2 { ->i2 : Symbol(i2, Decl(collisionArgumentsInterfaceMembers.ts, 9, 1)) +>i2 : Symbol(i2, Decl(collisionArgumentsInterfaceMembers.ts, 10, 1)) new (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 13, 9)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 13, 19)) +>i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 14, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 14, 19)) } interface i21 { ->i21 : Symbol(i21, Decl(collisionArgumentsInterfaceMembers.ts, 14, 1)) +>i21 : Symbol(i21, Decl(collisionArgumentsInterfaceMembers.ts, 15, 1)) new (arguments: number, ...rest); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 16, 9)) ->rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 16, 27)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 17, 9)) +>rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 17, 27)) } interface i2NoError { ->i2NoError : Symbol(i2NoError, Decl(collisionArgumentsInterfaceMembers.ts, 17, 1)) +>i2NoError : Symbol(i2NoError, Decl(collisionArgumentsInterfaceMembers.ts, 18, 1)) new (arguments: number); // no error ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 19, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 20, 9)) } // method interface i3 { ->i3 : Symbol(i3, Decl(collisionArgumentsInterfaceMembers.ts, 20, 1)) +>i3 : Symbol(i3, Decl(collisionArgumentsInterfaceMembers.ts, 21, 1)) foo(i: number, ...arguments); // no error - no code gen ->foo : Symbol(i3.foo, Decl(collisionArgumentsInterfaceMembers.ts, 23, 14)) ->i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 24, 8)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 24, 18)) +>foo : Symbol(i3.foo, Decl(collisionArgumentsInterfaceMembers.ts, 24, 14)) +>i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 25, 8)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 25, 18)) foo1(arguments: number, ...rest); // no error - no code gen ->foo1 : Symbol(i3.foo1, Decl(collisionArgumentsInterfaceMembers.ts, 24, 33)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 25, 9)) ->rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 25, 27)) +>foo1 : Symbol(i3.foo1, Decl(collisionArgumentsInterfaceMembers.ts, 25, 33)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 26, 9)) +>rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 26, 27)) fooNoError(arguments: number); // no error ->fooNoError : Symbol(i3.fooNoError, Decl(collisionArgumentsInterfaceMembers.ts, 25, 37)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 26, 15)) +>fooNoError : Symbol(i3.fooNoError, Decl(collisionArgumentsInterfaceMembers.ts, 26, 37)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 27, 15)) } diff --git a/tests/baselines/reference/collisionArgumentsInterfaceMembers.types b/tests/baselines/reference/collisionArgumentsInterfaceMembers.types index 6edb0a7ebed..3563a25b0bd 100644 --- a/tests/baselines/reference/collisionArgumentsInterfaceMembers.types +++ b/tests/baselines/reference/collisionArgumentsInterfaceMembers.types @@ -1,4 +1,7 @@ === tests/cases/compiler/collisionArgumentsInterfaceMembers.ts === +"use strict"; +>"use strict" : "use strict" + // call interface i1 { >i1 : i1 diff --git a/tests/cases/compiler/collisionArgumentsFunction.ts b/tests/cases/compiler/collisionArgumentsFunction.ts index b90dee9ec11..d5136d9169a 100644 --- a/tests/cases/compiler/collisionArgumentsFunction.ts +++ b/tests/cases/compiler/collisionArgumentsFunction.ts @@ -36,9 +36,12 @@ function f4NoError(arguments: any) { // no error var arguments: any; // No error } -declare function f5(arguments: number, ...rest); // no codegen no error -declare function f5(arguments: string, ...rest); // no codegen no error -declare function f52(i: number, ...arguments); // no codegen no error -declare function f52(i: string, ...arguments); // no codegen no error -declare function f6(arguments: number); // no codegen no error -declare function f6(arguments: string); // no codegen no error \ No newline at end of file +namespace strict { + "use strict"; + declare function f5(arguments: number, ...rest); // no codegen no error + declare function f5(arguments: string, ...rest); // no codegen no error + declare function f52(i: number, ...arguments); // no codegen no error + declare function f52(i: string, ...arguments); // no codegen no error + declare function f6(arguments: number); // no codegen no error + declare function f6(arguments: string); // no codegen no error +} \ No newline at end of file diff --git a/tests/cases/compiler/collisionArgumentsInType.ts b/tests/cases/compiler/collisionArgumentsInType.ts index c9354ba0bae..13785ef669d 100644 --- a/tests/cases/compiler/collisionArgumentsInType.ts +++ b/tests/cases/compiler/collisionArgumentsInType.ts @@ -1,3 +1,4 @@ +"use strict"; var v1: (i: number, ...arguments) => void; // no error - no code gen var v12: (arguments: number, ...restParameters) => void; // no error - no code gen var v2: { diff --git a/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts b/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts index bfb280116e4..87b6b4503ac 100644 --- a/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts +++ b/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts @@ -1,3 +1,4 @@ +"use strict"; // call interface i1 { (i: number, ...arguments); // no error - no code gen From 2345ecdcb84ff91dc5a9b2221a9fccd1d43c670a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 1 May 2017 11:35:56 -0700 Subject: [PATCH 033/282] Suggest spelling for unknown symbols + properties --- src/compiler/checker.ts | 199 ++++++++++++++++++++------- src/compiler/diagnosticMessages.json | 13 +- src/compiler/types.ts | 2 + src/compiler/utilities.ts | 23 ++++ 4 files changed, 187 insertions(+), 50 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 18e57303c12..7b7aaf9937c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -204,7 +204,9 @@ namespace ts { // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType + getApparentType, + getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol, }; const tupleTypes: GenericType[] = []; @@ -840,7 +842,25 @@ namespace ts { // 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 // the given name can be found. - function resolveName(location: Node | undefined, name: string, meaning: SymbolFlags, nameNotFoundMessage: DiagnosticMessage, nameArg: string | Identifier): Symbol { + function resolveName( + location: Node | undefined, + name: string, + meaning: SymbolFlags, + nameNotFoundMessage: DiagnosticMessage, + nameArg: string | Identifier, + suggestedNameNotFoundMessage?: DiagnosticMessage): Symbol { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + + function resolveNameHelper( + location: Node | undefined, + name: string, + meaning: SymbolFlags, + nameNotFoundMessage: DiagnosticMessage, + nameArg: string | Identifier, + lookup: (symbols: SymbolTable, name: string, meaning: SymbolFlags) => Symbol, + suggestedNameNotFoundMessage?: DiagnosticMessage): Symbol { + const originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location let result: Symbol; let lastLocation: Node; let propertyWithInvalidInitializer: Node; @@ -851,7 +871,7 @@ namespace ts { loop: while (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 = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { let useResult = true; if (isFunctionLike(location) && lastLocation && lastLocation !== (location).body) { // symbol lookup restrictions for function-like declarations @@ -929,12 +949,12 @@ namespace ts { } } - if (result = getSymbol(moduleExports, name, meaning & SymbolFlags.ModuleMember)) { + if (result = lookup(moduleExports, name, meaning & SymbolFlags.ModuleMember)) { break loop; } break; case SyntaxKind.EnumDeclaration: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & SymbolFlags.EnumMember)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & SymbolFlags.EnumMember)) { break loop; } break; @@ -949,7 +969,7 @@ namespace ts { if (isClassLike(location.parent) && !(getModifierFlags(location) & ModifierFlags.Static)) { const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & SymbolFlags.Value)) { + if (lookup(ctor.locals, name, meaning & SymbolFlags.Value)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -959,7 +979,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & SymbolFlags.Type)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & SymbolFlags.Type)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -995,7 +1015,7 @@ namespace ts { grandparent = location.parent.parent; if (isClassLike(grandparent) || grandparent.kind === SyntaxKind.InterfaceDeclaration) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & SymbolFlags.Type)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & SymbolFlags.Type)) { error(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -1059,7 +1079,7 @@ namespace ts { } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { @@ -1070,7 +1090,16 @@ namespace ts { !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); + let suggestion: string | undefined; + if (suggestedNameNotFoundMessage) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); + } } } return undefined; @@ -10411,7 +10440,7 @@ namespace ts { function getResolvedSymbol(node: Identifier): Symbol { const links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node, Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -14051,44 +14080,6 @@ namespace ts { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode: Identifier, containingType: Type) { - let errorInfo: DiagnosticMessageChain; - if (containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) { - for (const subtype of (containingType as UnionType).types) { - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - - function markPropertyAsReferenced(prop: Symbol) { - if (prop && - noUnusedIdentifiers && - (prop.flags & SymbolFlags.ClassMember) && - prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) { - if (getCheckFlags(prop) & CheckFlags.Instantiated) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - - function isInPropertyInitializer(node: Node): boolean { - while (node) { - if (node.parent && node.parent.kind === SyntaxKind.PropertyDeclaration && (node.parent as PropertyDeclaration).initializer === node) { - return true; - } - node = node.parent; - } - return false; - } - function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { const type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -14152,6 +14143,116 @@ namespace ts { return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode: Identifier, containingType: Type) { + let errorInfo: DiagnosticMessageChain; + if (containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) { + for (const subtype of (containingType as UnionType).types) { + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + const suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + + function getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined { + const suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), SymbolFlags.Value); + return suggestion && suggestion.name; + } + + function getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string { + const result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, (symbols, name, meaning) => { + const symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 3. + * * Whose levenshtein distance is more than 0.7 of the length of the name + * (0.7 allows identifiers of length 3 to have a distance of 2 to allow for one substitution) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name: string, symbols: Symbol[], meaning: SymbolFlags): Symbol | undefined { + const worstDistance = name.length * 0.7; + let bestDistance = Number.MAX_VALUE; + let bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (const candidate of symbols) { + if (candidate.flags & meaning && candidate.name && Math.abs(candidate.name.length - name.length) < 4) { + const candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3) { + continue; + } + const distance = levenshtein(candidateName, name); + if (distance < 2) { + return candidate; + } + else if (distance < bestDistance && distance < worstDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + + function markPropertyAsReferenced(prop: Symbol) { + if (prop && + noUnusedIdentifiers && + (prop.flags & SymbolFlags.ClassMember) && + prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) { + if (getCheckFlags(prop) & CheckFlags.Instantiated) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + + function isInPropertyInitializer(node: Node): boolean { + while (node) { + if (node.parent && node.parent.kind === SyntaxKind.PropertyDeclaration && (node.parent as PropertyDeclaration).initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { const left = node.kind === SyntaxKind.PropertyAccessExpression ? (node).expression diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index b69adf708f2..b205cb85cb6 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1843,6 +1843,14 @@ "category": "Error", "code": 2550 }, + "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?": { + "category": "Error", + "code": 2551 + }, + "Cannot find name '{0}'. Did you mean '{1}'?": { + "category": "Error", + "code": 2552 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 @@ -3532,7 +3540,10 @@ "category": "Message", "code": 90021 }, - + "Change spelling to '{0}'.": { + "category": "Message", + "code": 90022 + }, "Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": { "category": "Error", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 57cf17f7100..a923a8fff73 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2545,6 +2545,8 @@ namespace ts { tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string; /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 646a7b22e3f..1ce2cf2c991 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4629,4 +4629,27 @@ namespace ts { export function unescapeIdentifier(identifier: string): string { return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier; } + + export function levenshtein(s1: string, s2: string): number { + let previous: number[] = new Array(s2.length + 1); + let current: number[] = new Array(s2.length + 1); + for (let i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (let i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (let j = 1; j < s2.length + 1; j++) { + current[j] = Math.min( + previous[j] + 1, + current[j - 1] + 1, + previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)) + } + // shift current back to previous, and then reuse previous' array + const tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } } From 1bff5b749ebe67fe56028f6f31319445f7d99e92 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 1 May 2017 11:41:01 -0700 Subject: [PATCH 034/282] Codefix:suggest spellings+update others w/new codes --- src/services/codefixes/fixAddMissingMember.ts | 5 +- src/services/codefixes/fixSpelling.ts | 53 +++++++++++++++++++ src/services/codefixes/fixes.ts | 1 + src/services/codefixes/importFixes.ts | 1 + src/services/tsconfig.json | 3 +- 5 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 src/services/codefixes/fixSpelling.ts diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 8e1d0ac2f29..ef0025d2b25 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -1,7 +1,8 @@ /* @internal */ namespace ts.codefix { registerCodeFix({ - errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1.code, + Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); @@ -135,4 +136,4 @@ namespace ts.codefix { return actions; } } -} \ No newline at end of file +} diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts new file mode 100644 index 00000000000..b58dab95002 --- /dev/null +++ b/src/services/codefixes/fixSpelling.ts @@ -0,0 +1,53 @@ +/* @internal */ +namespace ts.codefix { + registerCodeFix({ + errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + + function getActionsForCorrectSpelling(context: CodeFixContext): CodeAction[] | undefined { + const sourceFile = context.sourceFile; + + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + const node = getTokenAtPosition(sourceFile, context.span.start); + const checker = context.program.getTypeChecker(); + let suggestion: string; + if (node.kind === SyntaxKind.Identifier && isPropertyAccessExpression(node.parent)) { + const containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node as Identifier, containingType); + } + else { + const meaning = getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + + function convertSemanticMeaningToSymbolFlags(meaning: SemanticMeaning): SymbolFlags { + let flags = 0; + if (meaning & SemanticMeaning.Namespace) { + flags |= SymbolFlags.Namespace; + } + if (meaning & SemanticMeaning.Type) { + flags |= SymbolFlags.Type; + } + if (meaning & SemanticMeaning.Value) { + flags |= SymbolFlags.Value; + } + return flags; + } +} diff --git a/src/services/codefixes/fixes.ts b/src/services/codefixes/fixes.ts index ae1643dfa3b..c2e2509a28e 100644 --- a/src/services/codefixes/fixes.ts +++ b/src/services/codefixes/fixes.ts @@ -1,5 +1,6 @@ /// /// +/// /// /// /// diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 78c27a1276b..0bc18ce7667 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -116,6 +116,7 @@ namespace ts.codefix { registerCodeFix({ errorCodes: [ Diagnostics.Cannot_find_name_0.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, Diagnostics.Cannot_find_namespace_0.code, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ], diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 978195a31f6..fd7269d46dd 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -82,6 +82,7 @@ "formatting/tokenRange.ts", "codeFixProvider.ts", "codefixes/fixAddMissingMember.ts", + "codefixes/fixSpelling.ts", "codefixes/fixExtendsInterfaceBecomesImplements.ts", "codefixes/fixClassIncorrectlyImplementsInterface.ts", "codefixes/fixClassDoesntImplementInheritedAbstractMember.ts", @@ -94,4 +95,4 @@ "codefixes/unusedIdentifierFixes.ts", "codefixes/disableJsDiagnostics.ts" ] -} \ No newline at end of file +} From 2479c071f9f55de708aa1d7fc86543dc0bb3f486 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 1 May 2017 11:42:22 -0700 Subject: [PATCH 035/282] Update baselines --- ...ExportedAndNonExportedFunctions.errors.txt | 8 +- .../VariableDeclaration11_es6.errors.txt | 4 +- .../VariableDeclaration6_es6.errors.txt | 4 +- .../anonymousClassExpression2.errors.txt | 4 +- ...tRestElementWithErrorSourceType.errors.txt | 4 +- .../baselines/reference/autoLift2.errors.txt | 20 +- .../reference/badArrayIndex.errors.txt | 4 +- .../baselines/reference/baseCheck.errors.txt | 4 +- tests/baselines/reference/bases.errors.txt | 8 +- ...akInIterationOrSwitchStatement4.errors.txt | 4 +- ...annotInvokeNewOnIndexExpression.errors.txt | 4 +- .../checkJsxChildrenProperty4.errors.txt | 4 +- .../classExtendingPrimitive.errors.txt | 16 +- .../classExtendsEveryObjectType.errors.txt | 4 +- .../classExtendsEveryObjectType2.errors.txt | 4 +- ...assMemberWithMissingIdentifier2.errors.txt | 4 +- .../reference/complicatedPrivacy.errors.txt | 4 +- ...torWithIncompleteTypeAnnotation.errors.txt | 44 ++-- .../continueInIterationStatement4.errors.txt | 4 +- ...IntypeCheckInvocationExpression.errors.txt | 4 +- .../reference/createArray.errors.txt | 12 +- ...tructuringParameterDeclaration4.errors.txt | 4 +- .../reference/dottedModuleName.errors.txt | 4 +- ...errorMessageOnObjectLiteralType.errors.txt | 4 +- ...xportNonInitializedVariablesES6.errors.txt | 4 +- .../reference/externModule.errors.txt | 16 +- .../reference/fixSignatureCaching.errors.txt | 12 +- .../reference/innerModExport2.errors.txt | 4 +- .../letDeclarations-scopes2.errors.txt | 16 +- ...mUsingES6FeaturesWithOnlyES5Lib.errors.txt | 4 +- ...wExceptionVariableInCatchClause.errors.txt | 8 +- .../narrowFromAnyWithInstanceof.errors.txt | 8 +- .../narrowFromAnyWithTypePredicate.errors.txt | 8 +- .../newExpressionWithCast.errors.txt | 4 +- .../reference/newNonReferenceType.errors.txt | 8 +- .../reference/newOperator.errors.txt | 12 +- ...adingStaticFunctionsInFunctions.errors.txt | 8 +- ...rameterNamesInTypeParameterList.errors.txt | 24 +- .../reference/parser10.1.1-8gs.errors.txt | 4 +- .../reference/parser15.4.4.14-9-2.errors.txt | 4 +- ...erAccessAfterPostfixExpression1.errors.txt | 4 +- .../reference/parserRealSource10.errors.txt | 12 +- .../reference/parserRealSource11.errors.txt | 228 +++++++++--------- .../reference/parserRealSource13.errors.txt | 4 +- .../reference/parserRealSource7.errors.txt | 60 ++--- .../reference/parserRealSource8.errors.txt | 20 +- ...gularExpressionDivideAmbiguity1.errors.txt | 4 +- ...gularExpressionDivideAmbiguity2.errors.txt | 4 +- .../reference/parserS7.2_A1.5_T2.errors.txt | 8 +- .../reference/parserS7.3_A1.1_T2.errors.txt | 4 +- .../reference/parserS7.6_A4.2_T1.errors.txt | 132 +++++----- .../parserSkippedTokens16.errors.txt | 4 +- .../reference/parserSymbolIndexer5.errors.txt | 4 +- .../reference/parserUnicode1.errors.txt | 8 +- .../parserUnterminatedGeneric2.errors.txt | 16 +- ...akInIterationOrSwitchStatement4.errors.txt | 4 +- ...r_continueInIterationStatement4.errors.txt | 4 +- .../reference/parserharness.errors.txt | 180 +++++++------- .../reference/parserindenter.errors.txt | 4 +- .../primitiveTypeAssignment.errors.txt | 12 +- .../reference/privateIndexer2.errors.txt | 4 +- .../reference/propertyOrdering.errors.txt | 4 +- .../reference/propertySignatures.errors.txt | 4 +- .../reference/scanner10.1.1-8gs.errors.txt | 4 +- .../reference/scannerS7.2_A1.5_T2.errors.txt | 8 +- .../reference/scannerS7.3_A1.1_T2.errors.txt | 4 +- .../reference/scannerS7.6_A4.2_T1.errors.txt | 132 +++++----- .../reference/scannertest1.errors.txt | 44 ++-- .../reference/staticsInAFunction.errors.txt | 8 +- .../strictModeReservedWord.errors.txt | 4 +- .../thisTypeInFunctionsNegative.errors.txt | 4 +- .../tsxAttributeInvalidNames.errors.txt | 8 +- .../reference/typeAssertions.errors.txt | 8 +- .../typeGuardFunctionErrors.errors.txt | 32 +-- ...nstanceOfByConstructorSignature.errors.txt | 24 +- ...ersAndParametersInComputedNames.errors.txt | 4 +- .../reference/undeclaredMethod.errors.txt | 4 +- .../reference/undeclaredVarEmit.errors.txt | 4 +- .../fourslash/codeFixAddMissingMember3.ts | 2 +- .../importNameCodeFixExistingImport0.ts | 2 +- .../importNameCodeFixExistingImport1.ts | 2 +- .../importNameCodeFixExistingImport10.ts | 2 +- .../importNameCodeFixExistingImport11.ts | 2 +- .../importNameCodeFixExistingImport12.ts | 2 +- .../importNameCodeFixExistingImport2.ts | 4 +- .../importNameCodeFixExistingImport3.ts | 4 +- .../importNameCodeFixExistingImport4.ts | 2 +- .../importNameCodeFixExistingImport5.ts | 2 +- .../importNameCodeFixExistingImport6.ts | 2 +- .../importNameCodeFixExistingImport7.ts | 2 +- .../importNameCodeFixExistingImport8.ts | 2 +- .../importNameCodeFixExistingImport9.ts | 2 +- .../importNameCodeFixExistingImportEquals0.ts | 2 +- .../importNameCodeFixNewImportAmbient0.ts | 2 +- .../importNameCodeFixNewImportAmbient1.ts | 2 +- .../importNameCodeFixNewImportAmbient2.ts | 2 +- .../importNameCodeFixNewImportAmbient3.ts | 2 +- .../importNameCodeFixNewImportBaseUrl0.ts | 2 +- .../importNameCodeFixNewImportDefault0.ts | 2 +- .../importNameCodeFixNewImportFile0.ts | 2 +- .../importNameCodeFixNewImportFile1.ts | 2 +- .../importNameCodeFixNewImportFile2.ts | 2 +- .../importNameCodeFixNewImportNodeModules1.ts | 2 +- .../importNameCodeFixNewImportNodeModules2.ts | 2 +- .../importNameCodeFixNewImportNodeModules3.ts | 2 +- .../importNameCodeFixNewImportPaths0.ts | 2 +- .../importNameCodeFixNewImportPaths1.ts | 2 +- .../importNameCodeFixNewImportPaths2.ts | 2 +- .../importNameCodeFixNewImportRootDirs0.ts | 2 +- .../importNameCodeFixNewImportTypeRoots0.ts | 2 +- .../importNameCodeFixNewImportTypeRoots1.ts | 2 +- .../importNameCodeFixOptionalImport0.ts | 2 +- .../importNameCodeFixOptionalImport1.ts | 2 +- 113 files changed, 709 insertions(+), 709 deletions(-) diff --git a/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt b/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt index 96528577cbc..bf143b9224d 100644 --- a/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt +++ b/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(28,13): error TS2339: Property 'fn2' does not exist on type 'typeof A'. -tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(29,14): error TS2339: Property 'fng2' does not exist on type 'typeof A'. +tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(28,13): error TS2551: Property 'fn2' does not exist on type 'typeof A'. Did you mean 'fng'? +tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(29,14): error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'? ==== tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts (2 errors) ==== @@ -32,7 +32,7 @@ tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAnd // these should be errors since the functions are not exported var fn2 = A.fn2; ~~~ -!!! error TS2339: Property 'fn2' does not exist on type 'typeof A'. +!!! error TS2551: Property 'fn2' does not exist on type 'typeof A'. Did you mean 'fng'? var fng2 = A.fng2; ~~~~ -!!! error TS2339: Property 'fng2' does not exist on type 'typeof A'. \ No newline at end of file +!!! error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'? \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration11_es6.errors.txt b/tests/baselines/reference/VariableDeclaration11_es6.errors.txt index 8fa0a99ab67..87650509cce 100644 --- a/tests/baselines/reference/VariableDeclaration11_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration11_es6.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS1212: Identifier expected. 'let' is a reserved word in strict mode. -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS2304: Cannot find name 'let'. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS2552: Cannot find name 'let'. Did you mean 'Set'? ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2, ~~~ !!! error TS1212: Identifier expected. 'let' is a reserved word in strict mode. ~~~ -!!! error TS2304: Cannot find name 'let'. \ No newline at end of file +!!! error TS2552: Cannot find name 'let'. Did you mean 'Set'? \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration6_es6.errors.txt b/tests/baselines/reference/VariableDeclaration6_es6.errors.txt index fb2a41b8739..440a2ee3ce5 100644 --- a/tests/baselines/reference/VariableDeclaration6_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration6_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration6_es6.ts(1,1): error TS2304: Cannot find name 'let'. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration6_es6.ts(1,1): error TS2552: Cannot find name 'let'. Did you mean 'Set'? ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration6_es6.ts (1 errors) ==== let ~~~ -!!! error TS2304: Cannot find name 'let'. \ No newline at end of file +!!! error TS2552: Cannot find name 'let'. Did you mean 'Set'? \ No newline at end of file diff --git a/tests/baselines/reference/anonymousClassExpression2.errors.txt b/tests/baselines/reference/anonymousClassExpression2.errors.txt index c9b59ae9c4d..6bc858bc542 100644 --- a/tests/baselines/reference/anonymousClassExpression2.errors.txt +++ b/tests/baselines/reference/anonymousClassExpression2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2339: Property 'methodA' does not exist on type 'B'. +tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2551: Property 'methodA' does not exist on type 'B'. Did you mean 'methodB'? ==== tests/cases/compiler/anonymousClassExpression2.ts (1 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2339: Property methodB() { this.methodA; // error ~~~~~~~ -!!! error TS2339: Property 'methodA' does not exist on type 'B'. +!!! error TS2551: Property 'methodA' does not exist on type 'B'. Did you mean 'methodB'? this.methodB; // ok } } diff --git a/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt b/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt index 080aca5a7ac..ff79716cab8 100644 --- a/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt +++ b/tests/baselines/reference/assignmentRestElementWithErrorSourceType.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,5): error TS2304: Cannot find name 'c'. -tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS2304: Cannot find name 'tupel'. +tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS2552: Cannot find name 'tupel'. Did you mean 'tuple'? ==== tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS ~ !!! error TS2304: Cannot find name 'c'. ~~~~~ -!!! error TS2304: Cannot find name 'tupel'. \ No newline at end of file +!!! error TS2552: Cannot find name 'tupel'. Did you mean 'tuple'? \ No newline at end of file diff --git a/tests/baselines/reference/autoLift2.errors.txt b/tests/baselines/reference/autoLift2.errors.txt index 9af3d59420f..1111a3750d8 100644 --- a/tests/baselines/reference/autoLift2.errors.txt +++ b/tests/baselines/reference/autoLift2.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/autoLift2.ts(5,14): error TS2339: Property 'foo' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(5,17): error TS1005: ';' expected. -tests/cases/compiler/autoLift2.ts(5,19): error TS2304: Cannot find name 'any'. -tests/cases/compiler/autoLift2.ts(6,14): error TS2339: Property 'bar' does not exist on type 'A'. +tests/cases/compiler/autoLift2.ts(5,19): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/autoLift2.ts(6,14): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? tests/cases/compiler/autoLift2.ts(6,17): error TS1005: ';' expected. -tests/cases/compiler/autoLift2.ts(6,19): error TS2304: Cannot find name 'any'. +tests/cases/compiler/autoLift2.ts(6,19): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/compiler/autoLift2.ts(12,11): error TS2339: Property 'foo' does not exist on type 'A'. -tests/cases/compiler/autoLift2.ts(14,11): error TS2339: Property 'bar' does not exist on type 'A'. +tests/cases/compiler/autoLift2.ts(14,11): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? tests/cases/compiler/autoLift2.ts(16,33): error TS2339: Property 'foo' does not exist on type 'A'. -tests/cases/compiler/autoLift2.ts(18,33): error TS2339: Property 'bar' does not exist on type 'A'. +tests/cases/compiler/autoLift2.ts(18,33): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? ==== tests/cases/compiler/autoLift2.ts (10 errors) ==== @@ -21,14 +21,14 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2339: Property 'bar' does not ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? this.bar: any; ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'A'. +!!! error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? } @@ -40,7 +40,7 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2339: Property 'bar' does not this.bar = "bar"; ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'A'. +!!! error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? [1, 2].forEach((p) => this.foo); ~~~ @@ -48,7 +48,7 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2339: Property 'bar' does not [1, 2].forEach((p) => this.bar); ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'A'. +!!! error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? } diff --git a/tests/baselines/reference/badArrayIndex.errors.txt b/tests/baselines/reference/badArrayIndex.errors.txt index 4830ff1f693..12aec4d45f4 100644 --- a/tests/baselines/reference/badArrayIndex.errors.txt +++ b/tests/baselines/reference/badArrayIndex.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/badArrayIndex.ts(1,15): error TS2304: Cannot find name 'number'. +tests/cases/compiler/badArrayIndex.ts(1,15): error TS2552: Cannot find name 'number'. Did you mean 'Number'? tests/cases/compiler/badArrayIndex.ts(1,22): error TS1109: Expression expected. ==== tests/cases/compiler/badArrayIndex.ts (2 errors) ==== var results = number[]; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? ~ !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/baseCheck.errors.txt b/tests/baselines/reference/baseCheck.errors.txt index 1f267f55301..1353d6e1a08 100644 --- a/tests/baselines/reference/baseCheck.errors.txt +++ b/tests/baselines/reference/baseCheck.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/baseCheck.ts(9,18): error TS2304: Cannot find name 'loc'. +tests/cases/compiler/baseCheck.ts(9,18): error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'? tests/cases/compiler/baseCheck.ts(17,53): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/baseCheck.ts(17,59): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/baseCheck.ts(18,62): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. @@ -20,7 +20,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'. constructor(x: number) { super(0, loc); ~~~ -!!! error TS2304: Cannot find name 'loc'. +!!! error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'? } m() { diff --git a/tests/baselines/reference/bases.errors.txt b/tests/baselines/reference/bases.errors.txt index a61d35f664e..974d5accfc4 100644 --- a/tests/baselines/reference/bases.errors.txt +++ b/tests/baselines/reference/bases.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/bases.ts(7,14): error TS2339: Property 'y' does not exist on type 'B'. tests/cases/compiler/bases.ts(7,15): error TS1005: ';' expected. -tests/cases/compiler/bases.ts(7,17): error TS2304: Cannot find name 'any'. +tests/cases/compiler/bases.ts(7,17): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/compiler/bases.ts(11,7): error TS2420: Class 'C' incorrectly implements interface 'I'. Property 'x' is missing in type 'C'. tests/cases/compiler/bases.ts(12,5): error TS2377: Constructors for derived classes must contain a 'super' call. tests/cases/compiler/bases.ts(13,9): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/bases.ts(13,14): error TS2339: Property 'x' does not exist on type 'C'. tests/cases/compiler/bases.ts(13,15): error TS1005: ';' expected. -tests/cases/compiler/bases.ts(13,17): error TS2304: Cannot find name 'any'. +tests/cases/compiler/bases.ts(13,17): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/compiler/bases.ts(17,9): error TS2339: Property 'x' does not exist on type 'C'. tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist on type 'C'. @@ -25,7 +25,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? } } @@ -44,7 +44,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? } ~~~~~ !!! error TS2377: Constructors for derived classes must contain a 'super' call. diff --git a/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt b/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt index c331ff09c2c..44e2d197f5a 100644 --- a/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt +++ b/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/breakInIterationOrSwitchStatement4.ts(1,15): error TS2304: Cannot find name 'something'. +tests/cases/compiler/breakInIterationOrSwitchStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? ==== tests/cases/compiler/breakInIterationOrSwitchStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2304: Cannot find name 'something'. +!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? break; } \ No newline at end of file diff --git a/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt b/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt index 7be5a1f086c..5e1b869c057 100644 --- a/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt +++ b/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2304: Cannot find name 'any'. +tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? ==== tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts (1 errors) ==== var test: any[] = new any[1]; ~~~ -!!! error TS2304: Cannot find name 'any'. \ No newline at end of file +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt index d12c557102c..399b159f482 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(24,28): error TS2339: Property 'NAme' does not exist on type 'IUser'. +tests/cases/conformance/jsx/file.tsx(24,28): error TS2551: Property 'NAme' does not exist on type 'IUser'. Did you mean 'Name'? tests/cases/conformance/jsx/file.tsx(32,9): error TS2322: Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & IFetchUserProps & { children?: ReactNode; }'. Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IFetchUserProps'. Types of property 'children' are incompatible. @@ -32,7 +32,7 @@ tests/cases/conformance/jsx/file.tsx(32,9): error TS2322: Type '{ children: ((us { user => (

{ user.NAme }

~~~~ -!!! error TS2339: Property 'NAme' does not exist on type 'IUser'. +!!! error TS2551: Property 'NAme' does not exist on type 'IUser'. Did you mean 'Name'? ) }
); diff --git a/tests/baselines/reference/classExtendingPrimitive.errors.txt b/tests/baselines/reference/classExtendingPrimitive.errors.txt index 554e0fbecbc..fc2e5bd5ad7 100644 --- a/tests/baselines/reference/classExtendingPrimitive.errors.txt +++ b/tests/baselines/reference/classExtendingPrimitive.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2304: Cannot find name 'number'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2304: Cannot find name 'string'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2304: Cannot find name 'boolean'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(6,18): error TS2304: Cannot find name 'Void'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(7,19): error TS1109: Expression expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(8,18): error TS2304: Cannot find name 'Null'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(10,18): error TS2507: Type 'undefined' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(11,18): error TS2304: Cannot find name 'Undefined'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(11,18): error TS2552: Cannot find name 'Undefined'. Did you mean 'undefined'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(14,18): error TS2507: Type 'typeof E' is not a constructor function type. @@ -14,13 +14,13 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla class C extends number { } ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? class C2 extends string { } ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? class C3 extends boolean { } ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? class C4 extends Void { } ~~~~ !!! error TS2304: Cannot find name 'Void'. @@ -36,7 +36,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla !!! error TS2507: Type 'undefined' is not a constructor function type. class C7 extends Undefined { } ~~~~~~~~~ -!!! error TS2304: Cannot find name 'Undefined'. +!!! error TS2552: Cannot find name 'Undefined'. Did you mean 'undefined'? enum E { A } class C8 extends E { } diff --git a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt index e1c5137e3a9..7c624b3b284 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(4,17): error TS2689: Cannot extend an interface 'I'. Did you mean 'implements'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2304: Cannot find name 'string'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,31): error TS1005: ',' expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(8,18): error TS2507: Type '{ foo: string; }' is not a constructor function type. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(11,18): error TS2507: Type 'typeof M' is not a constructor function type. @@ -20,7 +20,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla ~~~~~~~~~~~~~~~~ !!! error TS2507: Type '{ foo: any; }' is not a constructor function type. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ',' expected. var x: { foo: string; } diff --git a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt index af52a248b54..e92761884ea 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2304: Cannot find name 'string'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,31): error TS1005: ',' expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(3,18): error TS2507: Type 'undefined[]' is not a constructor function type. @@ -9,7 +9,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla ~~~~~~~~~~~~~~~~ !!! error TS2507: Type '{ foo: any; }' is not a constructor function type. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ',' expected. diff --git a/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt index b21e062e3b0..d0459214fd1 100644 --- a/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt +++ b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,11): error TS1146: D tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,12): error TS1005: '=' expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,14): error TS2304: Cannot find name 'name'. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,18): error TS1005: ']' expected. -tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2304: Cannot find name 'string'. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,25): error TS1005: ',' expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,26): error TS1136: Property assignment expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: Cannot find name 'VariableDeclaration'. @@ -20,7 +20,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: C ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/complicatedPrivacy.errors.txt b/tests/baselines/reference/complicatedPrivacy.errors.txt index c81605a5a83..ccf0b4fa025 100644 --- a/tests/baselines/reference/complicatedPrivacy.errors.txt +++ b/tests/baselines/reference/complicatedPrivacy.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/complicatedPrivacy.ts(11,24): error TS1054: A 'get' accessor cannot have parameters. tests/cases/compiler/complicatedPrivacy.ts(35,5): error TS1170: A computed property name in a type literal must directly refer to a built-in symbol. -tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2304: Cannot find name 'number'. +tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2552: Cannot find name 'number'. Did you mean 'Number'? tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo5' has no exported member 'i6'. @@ -45,7 +45,7 @@ tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo ~~~~~~~~ !!! error TS1170: A computed property name in a type literal must directly refer to a built-in symbol. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? }) { } diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index a572e0b34c8..99d1e48bf28 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -50,39 +50,39 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(227,13): error T tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(234,14): error TS1005: '{' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,9): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,16): error TS2304: Cannot find name 'method1'. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2304: Cannot find name 'val'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2552: Cannot find name 'val'. Did you mean 'eval'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,27): error TS1005: ',' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2304: Cannot find name 'number'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2552: Cannot find name 'number'. Did you mean 'Number'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,36): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,9): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,16): error TS2304: Cannot find name 'method2'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,26): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(241,5): error TS1128: Declaration or statement expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(246,25): error TS2339: Property 'method1' does not exist on type 'B'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(246,25): error TS2551: Property 'method1' does not exist on type 'B'. Did you mean 'method2'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,9): error TS2390: Constructor implementation is missing. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,21): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,44): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,69): error TS1110: Type expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,9): error TS1128: Declaration or statement expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2304: Cannot find name 'Overloads'. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2304: Cannot find name 'value'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2552: Cannot find name 'value'. Did you mean 'eval'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,31): error TS1005: ',' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,9): error TS1128: Declaration or statement expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2304: Cannot find name 'Overloads'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,27): error TS1135: Argument expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,33): error TS1005: '(' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,43): error TS1109: Expression expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,60): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,65): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,9): error TS2304: Cannot find name 'public'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS2304: Cannot find name 'DefaultValue'. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2304: Cannot find name 'value'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2552: Cannot find name 'value'. Did you mean 'eval'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,35): error TS1109: Expression expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2304: Cannot find name 'string'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,55): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS1128: Declaration or statement expected. @@ -431,11 +431,11 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~~ !!! error TS2304: Cannot find name 'method1'. ~~~ -!!! error TS2304: Cannot find name 'val'. +!!! error TS2552: Cannot find name 'val'. Did you mean 'eval'? ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? ~ !!! error TS1005: ';' expected. return val; @@ -458,7 +458,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS public method2() { return this.method1(2); ~~~~~~~ -!!! error TS2339: Property 'method1' does not exist on type 'B'. +!!! error TS2551: Property 'method1' does not exist on type 'B'. Did you mean 'method2'? } } @@ -480,28 +480,28 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~~~~~~ -!!! error TS2304: Cannot find name 'Overloads'. +!!! error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? ~~~~~ -!!! error TS2304: Cannot find name 'value'. +!!! error TS2552: Cannot find name 'value'. Did you mean 'eval'? ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? public Overloads( while : string, ...rest: string[]) { & ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~~~~~~ -!!! error TS2304: Cannot find name 'Overloads'. +!!! error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? ~~~~~ !!! error TS1135: Argument expression expected. ~ !!! error TS1005: '(' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~~~ !!! error TS1109: Expression expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ';' expected. ~ @@ -515,11 +515,11 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DefaultValue'. ~~~~~ -!!! error TS2304: Cannot find name 'value'. +!!! error TS2552: Cannot find name 'value'. Did you mean 'eval'? ~ !!! error TS1109: Expression expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/continueInIterationStatement4.errors.txt b/tests/baselines/reference/continueInIterationStatement4.errors.txt index bbc20570547..24bed78aeca 100644 --- a/tests/baselines/reference/continueInIterationStatement4.errors.txt +++ b/tests/baselines/reference/continueInIterationStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/continueInIterationStatement4.ts(1,15): error TS2304: Cannot find name 'something'. +tests/cases/compiler/continueInIterationStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? ==== tests/cases/compiler/continueInIterationStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2304: Cannot find name 'something'. +!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? continue; } \ No newline at end of file diff --git a/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt b/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt index a1f5afbde13..e1bcb5fcb69 100644 --- a/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt +++ b/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(6,28): error TS2304: Cannot find name 'task'. -tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(8,18): error TS2304: Cannot find name 'path'. +tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(8,18): error TS2552: Cannot find name 'path'. Did you mean 'Math'? tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(9,19): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(10,50): error TS2304: Cannot find name 'moduleType'. @@ -16,7 +16,7 @@ tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(10,50): error TS230 var folder = path.join(), ~~~~ -!!! error TS2304: Cannot find name 'path'. +!!! error TS2552: Cannot find name 'path'. Did you mean 'Math'? fileset = nake.fileSetSync(folder) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2347: Untyped function calls may not accept type arguments. diff --git a/tests/baselines/reference/createArray.errors.txt b/tests/baselines/reference/createArray.errors.txt index 31f6b880030..e562abd282c 100644 --- a/tests/baselines/reference/createArray.errors.txt +++ b/tests/baselines/reference/createArray.errors.txt @@ -1,16 +1,16 @@ -tests/cases/compiler/createArray.ts(1,12): error TS2304: Cannot find name 'number'. +tests/cases/compiler/createArray.ts(1,12): error TS2552: Cannot find name 'number'. Did you mean 'Number'? tests/cases/compiler/createArray.ts(1,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/compiler/createArray.ts(6,6): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/createArray.ts(7,12): error TS2304: Cannot find name 'boolean'. +tests/cases/compiler/createArray.ts(7,12): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? tests/cases/compiler/createArray.ts(7,19): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/createArray.ts(8,12): error TS2304: Cannot find name 'string'. +tests/cases/compiler/createArray.ts(8,12): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. ==== tests/cases/compiler/createArray.ts (7 errors) ==== var na=new number[]; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. @@ -22,12 +22,12 @@ tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be use !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var ba=new boolean[]; ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var sa=new string[]; ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. function f(s:string):number { return 0; diff --git a/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt b/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt index 8db71591f47..cdc7938d1af 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt +++ b/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt @@ -3,7 +3,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts( tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(14,17): error TS1047: A rest parameter cannot be optional. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(15,16): error TS1048: A rest parameter cannot have an initializer. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(20,19): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. -tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(21,7): error TS2304: Cannot find name 'array2'. +tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(21,7): error TS2552: Cannot find name 'array2'. Did you mean 'Array'? tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(22,4): error TS2345: Argument of type '[number, number, string, boolean, boolean]' is not assignable to parameter of type '[any, any, [[any]]]'. Types of property '2' are incompatible. Type 'string' is not assignable to type '[[any]]'. @@ -50,7 +50,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts( !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. a1(...array2); // Error parameter type is (number|string)[] ~~~~~~ -!!! error TS2304: Cannot find name 'array2'. +!!! error TS2552: Cannot find name 'array2'. Did you mean 'Array'? a5([1, 2, "string", false, true]); // Error, parameter type is [any, any, [[any]]] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[number, number, string, boolean, boolean]' is not assignable to parameter of type '[any, any, [[any]]]'. diff --git a/tests/baselines/reference/dottedModuleName.errors.txt b/tests/baselines/reference/dottedModuleName.errors.txt index afb8b944355..a2fa71430f8 100644 --- a/tests/baselines/reference/dottedModuleName.errors.txt +++ b/tests/baselines/reference/dottedModuleName.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/dottedModuleName.ts(3,29): error TS1144: '{' or ';' expected. -tests/cases/compiler/dottedModuleName.ts(3,33): error TS2304: Cannot find name 'x'. +tests/cases/compiler/dottedModuleName.ts(3,33): error TS2552: Cannot find name 'x'. Did you mean 'X'? ==== tests/cases/compiler/dottedModuleName.ts (2 errors) ==== @@ -9,7 +9,7 @@ tests/cases/compiler/dottedModuleName.ts(3,33): error TS2304: Cannot find name ' ~~ !!! error TS1144: '{' or ';' expected. ~ -!!! error TS2304: Cannot find name 'x'. +!!! error TS2552: Cannot find name 'x'. Did you mean 'X'? export module X.Y.Z { export var v2=f(v); } diff --git a/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt b/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt index bf9006a7143..7dffc9053e3 100644 --- a/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt +++ b/tests/baselines/reference/errorMessageOnObjectLiteralType.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/errorMessageOnObjectLiteralType.ts(5,3): error TS2339: Property 'getOwnPropertyNamess' does not exist on type '{ a: string; b: number; }'. -tests/cases/compiler/errorMessageOnObjectLiteralType.ts(6,8): error TS2339: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. +tests/cases/compiler/errorMessageOnObjectLiteralType.ts(6,8): error TS2551: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. Did you mean 'getOwnPropertyNames'? ==== tests/cases/compiler/errorMessageOnObjectLiteralType.ts (2 errors) ==== @@ -12,4 +12,4 @@ tests/cases/compiler/errorMessageOnObjectLiteralType.ts(6,8): error TS2339: Prop !!! error TS2339: Property 'getOwnPropertyNamess' does not exist on type '{ a: string; b: number; }'. Object.getOwnPropertyNamess(null); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2339: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. \ No newline at end of file +!!! error TS2551: Property 'getOwnPropertyNamess' does not exist on type 'ObjectConstructor'. Did you mean 'getOwnPropertyNames'? \ No newline at end of file diff --git a/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt b/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt index 84f9bcb59a4..60850c06b6d 100644 --- a/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt +++ b/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(1,4): error TS1123: Variable declaration list cannot be empty. tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(2,1): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. -tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(2,1): error TS2304: Cannot find name 'let'. +tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(2,1): error TS2552: Cannot find name 'let'. Did you mean 'Set'? tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(3,6): error TS1123: Variable declaration list cannot be empty. @@ -12,7 +12,7 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(3,6) ~~~ !!! error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. ~~~ -!!! error TS2304: Cannot find name 'let'. +!!! error TS2552: Cannot find name 'let'. Did you mean 'Set'? const; !!! error TS1123: Variable declaration list cannot be empty. diff --git a/tests/baselines/reference/externModule.errors.txt b/tests/baselines/reference/externModule.errors.txt index 8d4126350c1..d6659c1d548 100644 --- a/tests/baselines/reference/externModule.errors.txt +++ b/tests/baselines/reference/externModule.errors.txt @@ -8,10 +8,10 @@ tests/cases/compiler/externModule.ts(18,6): error TS2390: Constructor implementa tests/cases/compiler/externModule.ts(20,13): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/externModule.ts(26,13): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/externModule.ts(28,13): error TS2391: Function implementation is missing or not immediately following the declaration. -tests/cases/compiler/externModule.ts(32,11): error TS2304: Cannot find name 'XDate'. -tests/cases/compiler/externModule.ts(34,7): error TS2304: Cannot find name 'XDate'. -tests/cases/compiler/externModule.ts(36,7): error TS2304: Cannot find name 'XDate'. -tests/cases/compiler/externModule.ts(37,3): error TS2304: Cannot find name 'XDate'. +tests/cases/compiler/externModule.ts(32,11): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? +tests/cases/compiler/externModule.ts(34,7): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? +tests/cases/compiler/externModule.ts(36,7): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? +tests/cases/compiler/externModule.ts(37,3): error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? ==== tests/cases/compiler/externModule.ts (14 errors) ==== @@ -68,17 +68,17 @@ tests/cases/compiler/externModule.ts(37,3): error TS2304: Cannot find name 'XDat var d=new XDate(); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? d.getDay(); d=new XDate(1978,2); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? d.getXDate(); var n=XDate.parse("3/2/2004"); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? n=XDate.UTC(1964,2,1); ~~~~~ -!!! error TS2304: Cannot find name 'XDate'. +!!! error TS2552: Cannot find name 'XDate'. Did you mean 'Date'? \ No newline at end of file diff --git a/tests/baselines/reference/fixSignatureCaching.errors.txt b/tests/baselines/reference/fixSignatureCaching.errors.txt index 7a5c43c966e..573857d6cb2 100644 --- a/tests/baselines/reference/fixSignatureCaching.errors.txt +++ b/tests/baselines/reference/fixSignatureCaching.errors.txt @@ -64,9 +64,9 @@ tests/cases/conformance/fixSignatureCaching.ts(970,18): error TS2339: Property ' tests/cases/conformance/fixSignatureCaching.ts(975,16): error TS2304: Cannot find name 'module'. tests/cases/conformance/fixSignatureCaching.ts(975,42): error TS2304: Cannot find name 'module'. tests/cases/conformance/fixSignatureCaching.ts(976,37): error TS2304: Cannot find name 'module'. -tests/cases/conformance/fixSignatureCaching.ts(977,23): error TS2304: Cannot find name 'define'. -tests/cases/conformance/fixSignatureCaching.ts(977,48): error TS2304: Cannot find name 'define'. -tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2304: Cannot find name 'define'. +tests/cases/conformance/fixSignatureCaching.ts(977,23): error TS2552: Cannot find name 'define'. Did you mean 'undefined'? +tests/cases/conformance/fixSignatureCaching.ts(977,48): error TS2552: Cannot find name 'define'. Did you mean 'undefined'? +tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2552: Cannot find name 'define'. Did you mean 'undefined'? tests/cases/conformance/fixSignatureCaching.ts(979,23): error TS2304: Cannot find name 'window'. tests/cases/conformance/fixSignatureCaching.ts(980,37): error TS2304: Cannot find name 'window'. @@ -1182,12 +1182,12 @@ tests/cases/conformance/fixSignatureCaching.ts(980,37): error TS2304: Cannot fin !!! error TS2304: Cannot find name 'module'. } else if (typeof define === 'function' && define.amd) { ~~~~~~ -!!! error TS2304: Cannot find name 'define'. +!!! error TS2552: Cannot find name 'define'. Did you mean 'undefined'? ~~~~~~ -!!! error TS2304: Cannot find name 'define'. +!!! error TS2552: Cannot find name 'define'. Did you mean 'undefined'? return define; ~~~~~~ -!!! error TS2304: Cannot find name 'define'. +!!! error TS2552: Cannot find name 'define'. Did you mean 'undefined'? } else if (typeof window !== 'undefined') { ~~~~~~ !!! error TS2304: Cannot find name 'window'. diff --git a/tests/baselines/reference/innerModExport2.errors.txt b/tests/baselines/reference/innerModExport2.errors.txt index f9568bb45a4..edd22daca41 100644 --- a/tests/baselines/reference/innerModExport2.errors.txt +++ b/tests/baselines/reference/innerModExport2.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/innerModExport2.ts(5,5): error TS2304: Cannot find name 'mo tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected. tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. -tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExportFunc' does not exist on type 'typeof Outer'. +tests/cases/compiler/innerModExport2.ts(20,7): error TS2551: Property 'NonExportFunc' does not exist on type 'typeof Outer'. Did you mean 'ExportFunc'? ==== tests/cases/compiler/innerModExport2.ts (5 errors) ==== @@ -35,4 +35,4 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport Outer.NonExportFunc(); ~~~~~~~~~~~~~ -!!! error TS2339: Property 'NonExportFunc' does not exist on type 'typeof Outer'. \ No newline at end of file +!!! error TS2551: Property 'NonExportFunc' does not exist on type 'typeof Outer'. Did you mean 'ExportFunc'? \ No newline at end of file diff --git a/tests/baselines/reference/letDeclarations-scopes2.errors.txt b/tests/baselines/reference/letDeclarations-scopes2.errors.txt index 8e0cf04aa14..e451eb0ad07 100644 --- a/tests/baselines/reference/letDeclarations-scopes2.errors.txt +++ b/tests/baselines/reference/letDeclarations-scopes2.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/letDeclarations-scopes2.ts(8,5): error TS2304: Cannot find name 'local2'. -tests/cases/compiler/letDeclarations-scopes2.ts(20,5): error TS2304: Cannot find name 'local2'. -tests/cases/compiler/letDeclarations-scopes2.ts(23,1): error TS2304: Cannot find name 'local'. -tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2304: Cannot find name 'local2'. +tests/cases/compiler/letDeclarations-scopes2.ts(8,5): error TS2552: Cannot find name 'local2'. Did you mean 'local'? +tests/cases/compiler/letDeclarations-scopes2.ts(20,5): error TS2552: Cannot find name 'local2'. Did you mean 'local'? +tests/cases/compiler/letDeclarations-scopes2.ts(23,1): error TS2552: Cannot find name 'local'. Did you mean 'global'? +tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2552: Cannot find name 'local2'. Did you mean 'global'? ==== tests/cases/compiler/letDeclarations-scopes2.ts (4 errors) ==== @@ -14,7 +14,7 @@ tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2304: Cannot find global; // OK local2; // Error ~~~~~~ -!!! error TS2304: Cannot find name 'local2'. +!!! error TS2552: Cannot find name 'local2'. Did you mean 'local'? { let local2 = 0; @@ -28,14 +28,14 @@ tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2304: Cannot find global; // OK local2; // Error ~~~~~~ -!!! error TS2304: Cannot find name 'local2'. +!!! error TS2552: Cannot find name 'local2'. Did you mean 'local'? } local; // Error ~~~~~ -!!! error TS2304: Cannot find name 'local'. +!!! error TS2552: Cannot find name 'local'. Did you mean 'global'? global; // OK local2; // Error ~~~~~~ -!!! error TS2304: Cannot find name 'local2'. +!!! error TS2552: Cannot find name 'local2'. Did you mean 'global'? \ No newline at end of file diff --git a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt index 80b8e345cde..b56b03de533 100644 --- a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt +++ b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(4,18): error TS2339: Property 'from' does not exist on type 'ArrayConstructor'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(10,13): error TS2304: Cannot find name 'Map'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(17,5): error TS2339: Property 'name' does not exist on type '() => void'. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2339: Property 'sign' does not exist on type 'Math'. +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(25,6): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(29,18): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(33,13): error TS2304: Cannot find name 'Proxy'. @@ -40,7 +40,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.t // Using ES6 math Math.sign(1); ~~~~ -!!! error TS2339: Property 'sign' does not exist on type 'Math'. +!!! error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? // Using ES6 object var o = { diff --git a/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt b/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt index e435b98050d..248d4c35473 100644 --- a/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt +++ b/tests/baselines/reference/narrowExceptionVariableInCatchClause.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(11,17): error TS2339: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. -tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(16,17): error TS2339: Property 'massage' does not exist on type 'Error'. +tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(11,17): error TS2551: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. Did you mean 'dontPanic'? +tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(16,17): error TS2551: Property 'massage' does not exist on type 'Error'. Did you mean 'message'? ==== tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts (2 errors) ==== @@ -15,14 +15,14 @@ tests/cases/conformance/types/any/narrowExceptionVariableInCatchClause.ts(16,17) err.dontPanic(); // OK err.doPanic(); // ERROR: Property 'doPanic' does not exist on type '{...}' ~~~~~~~ -!!! error TS2339: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. +!!! error TS2551: Property 'doPanic' does not exist on type '{ type: "foo"; dontPanic(): any; }'. Did you mean 'dontPanic'? } else if (err instanceof Error) { err.message; err.massage; // ERROR: Property 'massage' does not exist on type 'Error' ~~~~~~~ -!!! error TS2339: Property 'massage' does not exist on type 'Error'. +!!! error TS2551: Property 'massage' does not exist on type 'Error'. Did you mean 'message'? } else { diff --git a/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt b/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt index 3e152b0faf4..f8465651901 100644 --- a/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt +++ b/tests/baselines/reference/narrowFromAnyWithInstanceof.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(17,7): error TS2339: Property 'mesage' does not exist on type 'Error'. -tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(22,7): error TS2339: Property 'getHuors' does not exist on type 'Date'. +tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(17,7): error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? +tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(22,7): error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? ==== tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts (2 errors) ==== @@ -21,13 +21,13 @@ tests/cases/conformance/types/any/narrowFromAnyWithInstanceof.ts(22,7): error TS x.message; x.mesage; ~~~~~~ -!!! error TS2339: Property 'mesage' does not exist on type 'Error'. +!!! error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? } if (x instanceof Date) { x.getDate(); x.getHuors(); ~~~~~~~~ -!!! error TS2339: Property 'getHuors' does not exist on type 'Date'. +!!! error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? } \ No newline at end of file diff --git a/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt b/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt index c06c8a98801..4865748f332 100644 --- a/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt +++ b/tests/baselines/reference/narrowFromAnyWithTypePredicate.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(22,7): error TS2339: Property 'method' does not exist on type '{}'. tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(23,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures. -tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(28,7): error TS2339: Property 'mesage' does not exist on type 'Error'. -tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(33,7): error TS2339: Property 'getHuors' does not exist on type 'Date'. +tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(28,7): error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? +tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(33,7): error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? ==== tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts (4 errors) ==== @@ -38,13 +38,13 @@ tests/cases/conformance/types/any/narrowFromAnyWithTypePredicate.ts(33,7): error x.message; x.mesage; ~~~~~~ -!!! error TS2339: Property 'mesage' does not exist on type 'Error'. +!!! error TS2551: Property 'mesage' does not exist on type 'Error'. Did you mean 'message'? } if (isDate(x)) { x.getDate(); x.getHuors(); ~~~~~~~~ -!!! error TS2339: Property 'getHuors' does not exist on type 'Date'. +!!! error TS2551: Property 'getHuors' does not exist on type 'Date'. Did you mean 'getHours'? } \ No newline at end of file diff --git a/tests/baselines/reference/newExpressionWithCast.errors.txt b/tests/baselines/reference/newExpressionWithCast.errors.txt index 4fc4ee24d8c..158856f7beb 100644 --- a/tests/baselines/reference/newExpressionWithCast.errors.txt +++ b/tests/baselines/reference/newExpressionWithCast.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/newExpressionWithCast.ts(3,12): error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type. tests/cases/compiler/newExpressionWithCast.ts(7,13): error TS2365: Operator '>' cannot be applied to types 'boolean' and 'void'. tests/cases/compiler/newExpressionWithCast.ts(7,17): error TS1109: Expression expected. -tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2304: Cannot find name 'any'. +tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? ==== tests/cases/compiler/newExpressionWithCast.ts (4 errors) ==== @@ -19,7 +19,7 @@ tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2304: Cannot find n ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? function Test3() { } // valid with noImplicitAny diff --git a/tests/baselines/reference/newNonReferenceType.errors.txt b/tests/baselines/reference/newNonReferenceType.errors.txt index a68eba9b9e7..4cf478b6e22 100644 --- a/tests/baselines/reference/newNonReferenceType.errors.txt +++ b/tests/baselines/reference/newNonReferenceType.errors.txt @@ -1,12 +1,12 @@ -tests/cases/compiler/newNonReferenceType.ts(1,13): error TS2304: Cannot find name 'any'. -tests/cases/compiler/newNonReferenceType.ts(2,13): error TS2304: Cannot find name 'boolean'. +tests/cases/compiler/newNonReferenceType.ts(1,13): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/newNonReferenceType.ts(2,13): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? ==== tests/cases/compiler/newNonReferenceType.ts (2 errors) ==== var a = new any(); ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? var b = new boolean(); // error ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? \ No newline at end of file diff --git a/tests/baselines/reference/newOperator.errors.txt b/tests/baselines/reference/newOperator.errors.txt index fc6f22d9eac..6c07677acd3 100644 --- a/tests/baselines/reference/newOperator.errors.txt +++ b/tests/baselines/reference/newOperator.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/newOperator.ts(3,13): error TS2693: 'ifc' only refers to a type, but is being used as a value here. tests/cases/compiler/newOperator.ts(10,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/compiler/newOperator.ts(11,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -tests/cases/compiler/newOperator.ts(12,5): error TS2304: Cannot find name 'string'. -tests/cases/compiler/newOperator.ts(18,14): error TS2304: Cannot find name 'string'. +tests/cases/compiler/newOperator.ts(12,5): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/newOperator.ts(18,14): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/newOperator.ts(18,20): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/newOperator.ts(21,1): error TS2304: Cannot find name 'string'. +tests/cases/compiler/newOperator.ts(21,1): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/newOperator.ts(22,1): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/compiler/newOperator.ts(28,13): error TS2304: Cannot find name 'q'. tests/cases/compiler/newOperator.ts(31,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. @@ -32,7 +32,7 @@ tests/cases/compiler/newOperator.ts(45,23): error TS1150: 'new T[]' cannot be us !!! error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. new string; ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? // Use in LHS of expression? (new Date()).toString(); @@ -40,14 +40,14 @@ tests/cases/compiler/newOperator.ts(45,23): error TS1150: 'new T[]' cannot be us // Various spacing var t3 = new string[]( ); ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var t4 = new string ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? [ ~ ] diff --git a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt index ae16b59b095..4aa261d9808 100644 --- a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt +++ b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt @@ -5,12 +5,12 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,3): error TS1128 tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,19): error TS1005: ',' expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2304: Cannot find name 'string'. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,3): error TS1128: Declaration or statement expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,20): error TS1109: Expression expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,21): error TS2304: Cannot find name 'any'. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS1005: ';' expected. @@ -33,7 +33,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? static test(name?:any){ } ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -44,7 +44,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? ~ !!! error TS1005: ';' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt b/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt index 54ddb963f94..c4e29ca62f9 100644 --- a/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt +++ b/tests/baselines/reference/parameterNamesInTypeParameterList.errors.txt @@ -1,44 +1,44 @@ -tests/cases/compiler/parameterNamesInTypeParameterList.ts(1,30): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(5,30): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(9,30): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(14,22): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(17,22): error TS2304: Cannot find name 'a'. -tests/cases/compiler/parameterNamesInTypeParameterList.ts(20,22): error TS2304: Cannot find name 'a'. +tests/cases/compiler/parameterNamesInTypeParameterList.ts(1,30): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(5,30): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(9,30): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(14,22): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(17,22): error TS2552: Cannot find name 'a'. Did you mean 'A'? +tests/cases/compiler/parameterNamesInTypeParameterList.ts(20,22): error TS2552: Cannot find name 'a'. Did you mean 'A'? ==== tests/cases/compiler/parameterNamesInTypeParameterList.ts (6 errors) ==== function f0(a: T) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b; } function f1({a}: {a:T}) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b; } function f2([a]: T[]) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b; } class A { m0(a: T) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b } m1({a}: {a:T}) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b } m2([a]: T[]) { ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? a.b } } \ No newline at end of file diff --git a/tests/baselines/reference/parser10.1.1-8gs.errors.txt b/tests/baselines/reference/parser10.1.1-8gs.errors.txt index 84e45644e94..442b90fc85e 100644 --- a/tests/baselines/reference/parser10.1.1-8gs.errors.txt +++ b/tests/baselines/reference/parser10.1.1-8gs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(16,7): error TS2304: Cannot find name 'NotEarlyError'. +tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(16,7): error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(17,5): error TS1212: Identifier expected. 'public' is a reserved word in strict mode. @@ -20,7 +20,7 @@ tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(17,5): error TS12 "use strict"; throw NotEarlyError; ~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'NotEarlyError'. +!!! error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? var public = 1; ~~~~~~ !!! error TS1212: Identifier expected. 'public' is a reserved word in strict mode. diff --git a/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt b/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt index 2c721724b3e..143592f649a 100644 --- a/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt +++ b/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(16,15): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate 'false'. -tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(25,1): error TS2304: Cannot find name 'runTestCase'. +tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(25,1): error TS2552: Cannot find name 'runTestCase'. Did you mean 'testcase'? ==== tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts (2 errors) ==== @@ -33,5 +33,5 @@ tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(25,1): error T } runTestCase(testcase); ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'runTestCase'. +!!! error TS2552: Cannot find name 'runTestCase'. Did you mean 'testcase'? \ No newline at end of file diff --git a/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt b/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt index 6af3f2843f6..6c2a0562a7c 100644 --- a/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt +++ b/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,1): error TS2304: Cannot find name 'a'. tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,4): error TS1005: ';' expected. -tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,5): error TS2304: Cannot find name 'toString'. +tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts(1,5): error TS2552: Cannot find name 'toString'. Did you mean 'String'? ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPostfixExpression1.ts (3 errors) ==== @@ -10,4 +10,4 @@ tests/cases/conformance/parser/ecmascript5/Expressions/parserMemberAccessAfterPo ~ !!! error TS1005: ';' expected. ~~~~~~~~ -!!! error TS2304: Cannot find name 'toString'. \ No newline at end of file +!!! error TS2552: Cannot find name 'toString'. Did you mean 'String'? \ No newline at end of file diff --git a/tests/baselines/reference/parserRealSource10.errors.txt b/tests/baselines/reference/parserRealSource10.errors.txt index ae48cd79b51..c6ab397d7d7 100644 --- a/tests/baselines/reference/parserRealSource10.errors.txt +++ b/tests/baselines/reference/parserRealSource10.errors.txt @@ -1,11 +1,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,33): error TS2449: Class 'TokenInfo' used before its declaration. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,36): error TS2304: Cannot find name 'string'. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,36): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,41): error TS2304: Cannot find name 'number'. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,41): error TS2552: Cannot find name 'number'. Did you mean 'Number'? tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,47): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,35): error TS2304: Cannot find name 'boolean'. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,35): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(179,54): error TS2304: Cannot find name 'ErrorRecoverySet'. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(184,28): error TS2304: Cannot find name 'ErrorRecoverySet'. @@ -479,17 +479,17 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(449,40): error !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var nodeTypeTable = new string[]; ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var nodeTypeToTokTable = new number[]; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var noRegexTable = new boolean[]; ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. diff --git a/tests/baselines/reference/parserRealSource11.errors.txt b/tests/baselines/reference/parserRealSource11.errors.txt index efae0f962fd..84264ee5512 100644 --- a/tests/baselines/reference/parserRealSource11.errors.txt +++ b/tests/baselines/reference/parserRealSource11.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(13,22): error TS2304: Cannot find name 'Type'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(14,24): error TS2304: Cannot find name 'ASTFlags'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(14,24): error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(17,38): error TS2304: Cannot find name 'CompilerDiagnostics'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(24,39): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(36,36): error TS2304: Cannot find name 'TypeFlow'. @@ -30,7 +30,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(103,22): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(108,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(119,31): error TS2304: Cannot find name 'PrintContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(130,17): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(130,37): error TS2304: Cannot find name 'ASTFlags'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(130,37): error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(137,17): error TS2304: Cannot find name 'nodeTypeTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(138,24): error TS2304: Cannot find name 'nodeTypeTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(141,30): error TS2304: Cannot find name 'NodeType'. @@ -46,7 +46,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(199,42): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(219,33): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(231,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(231,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(233,52): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(233,52): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(237,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(251,21): error TS2304: Cannot find name 'Symbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(268,19): error TS2304: Cannot find name 'NodeType'. @@ -85,35 +85,35 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(427,22): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(441,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(441,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(445,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(446,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(446,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(449,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(451,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(451,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(453,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(454,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(454,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(457,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(460,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(463,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(465,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(465,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(467,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(469,50): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(472,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(472,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(474,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(476,50): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(479,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(479,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(481,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(483,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(483,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(485,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(487,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(487,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(489,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(491,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(491,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(494,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(496,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(496,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(498,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(500,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(500,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(502,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(504,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(504,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(506,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(507,58): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(507,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(518,32): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(520,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(525,27): error TS2304: Cannot find name 'Signature'. @@ -174,26 +174,26 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(644,21): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(647,26): error TS2304: Cannot find name 'tokenTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(651,58): error TS2304: Cannot find name 'tokenTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(658,26): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(660,67): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(660,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(665,26): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(669,26): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(670,55): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(672,33): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(672,60): error TS2304: Cannot find name 'FncFlags'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(678,67): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(681,67): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(684,63): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(678,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(681,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(684,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(686,26): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(687,63): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(694,63): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(687,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(694,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(696,26): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(711,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(714,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(718,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(718,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(721,51): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(723,51): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(725,51): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(721,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(723,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(725,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(733,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(738,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(747,30): error TS2304: Cannot find name 'Emitter'. @@ -213,7 +213,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(837,30): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(837,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(838,24): error TS2304: Cannot find name 'ModuleType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(841,61): error TS2304: Cannot find name 'TypeSymbol'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(850,52): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(850,52): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(863,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(867,29): error TS1015: Parameter cannot have question mark and initializer. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(868,38): error TS2304: Cannot find name 'NodeType'. @@ -258,7 +258,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1024,47): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1032,36): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1033,29): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1034,28): error TS2304: Cannot find name 'BasicBlock'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1036,31): error TS2304: Cannot find name 'ControlFlowContext'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1036,31): error TS2552: Cannot find name 'ControlFlowContext'. Did you mean 'controlFlowPrefix'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1038,69): error TS2304: Cannot find name 'IAstWalker'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1043,26): error TS2304: Cannot find name 'getAstWalkerFactory'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1050,36): error TS2304: Cannot find name 'TypeFlow'. @@ -311,7 +311,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1164,47): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1164,97): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1172,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1172,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1176,60): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1176,60): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1187,32): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1195,27): error TS2304: Cannot find name 'ModuleFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1196,21): error TS2304: Cannot find name 'ModuleType'. @@ -343,7 +343,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1286,36): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1290,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1290,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1295,32): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1297,27): error TS2304: Cannot find name 'ASTFlags'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1297,27): error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1306,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1314,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1317,30): error TS2304: Cannot find name 'Emitter'. @@ -354,7 +354,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1339,26): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1348,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1351,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1351,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1362,67): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1362,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1374,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1375,37): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1388,36): error TS2304: Cannot find name 'TypeFlow'. @@ -370,7 +370,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1438,34): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1457,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1462,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1462,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1467,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1467,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1475,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1479,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1481,33): error TS2304: Cannot find name 'BasicBlock'. @@ -380,7 +380,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1490,39): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1515,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1518,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1518,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1528,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1528,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1535,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1539,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1541,33): error TS2304: Cannot find name 'BasicBlock'. @@ -389,7 +389,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1545,29): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1572,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1577,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1577,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1583,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1583,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1596,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1600,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1602,31): error TS2304: Cannot find name 'BasicBlock'. @@ -398,7 +398,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1615,39): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1651,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1654,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1654,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1660,63): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1660,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1670,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1675,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1682,19): error TS2304: Cannot find name 'NodeType'. @@ -416,8 +416,8 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1732,66): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1733,73): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1749,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1749,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1755,47): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1757,46): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1755,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1757,46): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1766,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1775,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1784,33): error TS2304: Cannot find name 'BasicBlock'. @@ -426,10 +426,10 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1811,19): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1816,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1816,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1822,43): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1823,55): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1827,65): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1831,47): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1833,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1823,55): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1827,65): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1831,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1833,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1841,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1845,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1850,33): error TS2304: Cannot find name 'BasicBlock'. @@ -443,13 +443,13 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1908,25): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1911,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1914,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1914,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1919,51): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1919,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1928,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1939,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1944,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1944,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1950,46): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1958,50): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1950,46): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1958,50): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1969,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1981,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1984,33): error TS2304: Cannot find name 'BasicBlock'. @@ -457,7 +457,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1985,35): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2014,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2017,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2017,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2022,51): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2022,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2033,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2042,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2043,33): error TS2304: Cannot find name 'BasicBlock'. @@ -466,21 +466,21 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2067,19): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2070,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2070,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2074,36): error TS2304: Cannot find name 'TypeFlow'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2077,28): error TS2304: Cannot find name 'getTypeLink'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2077,28): error TS2552: Cannot find name 'getTypeLink'. Did you mean 'typeLink'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2100,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2105,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2105,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2107,50): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2108,54): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2107,50): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2108,54): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2112,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2119,42): error TS2304: Cannot find name 'ControlFlowContext'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2120,36): error TS2304: Cannot find name 'BasicBlock'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2122,32): error TS2304: Cannot find name 'BasicBlock'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2120,36): error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2122,32): error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2145,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2150,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2150,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2153,50): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2154,52): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2153,50): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2154,52): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2159,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2161,32): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2164,37): error TS2304: Cannot find name 'BasicBlock'. @@ -489,7 +489,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2185,36): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2195,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2198,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2198,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2202,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2202,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2207,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2212,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2223,19): error TS2304: Cannot find name 'NodeType'. @@ -497,18 +497,18 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2225,40): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2229,32): error TS2304: Cannot find name 'SymbolScope'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2231,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2231,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2237,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2240,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2237,48): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2240,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2245,42): error TS2304: Cannot find name 'ControlFlowContext'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2248,36): error TS2304: Cannot find name 'BasicBlock'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2248,36): error TS2552: Cannot find name 'BasicBlock'. Did you mean 'bodBlock'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2259,36): error TS2304: Cannot find name 'TypeFlow'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2263,33): error TS2304: Cannot find name 'ValueLocation'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2263,33): error TS2552: Cannot find name 'ValueLocation'. Did you mean 'LocationInfo'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2264,30): error TS2304: Cannot find name 'VariableSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2269,38): error TS2304: Cannot find name 'TypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2300,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2303,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2303,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2307,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2307,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2312,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2320,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2331,19): error TS2304: Cannot find name 'NodeType'. @@ -537,7 +537,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'Type'. public flags = ASTFlags.Writeable; ~~~~~~~~ -!!! error TS2304: Cannot find name 'ASTFlags'. +!!! error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? // REVIEW: for diagnostic purposes public passCreated: number = CompilerDiagnostics.analysisPass; @@ -713,7 +713,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~ -!!! error TS2304: Cannot find name 'ASTFlags'. +!!! error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? lab += " (Error)"; } context.writeLine(lab); @@ -848,7 +848,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascriptList(this, null, TokenID.Semicolon, startLine, false, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); } @@ -1139,7 +1139,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput("++"); break; case NodeType.LogNot: @@ -1148,14 +1148,14 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("!"); emitter.emitJavascript(this.operand, TokenID.Exclamation, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.DecPost: ~~~~~~~~ !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput("--"); break; case NodeType.ObjectLit: @@ -1174,7 +1174,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("~"); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Neg: ~~~~~~~~ @@ -1187,7 +1187,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand, TokenID.Minus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Pos: ~~~~~~~~ @@ -1200,7 +1200,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand, TokenID.Plus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.IncPre: ~~~~~~~~ @@ -1208,7 +1208,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("++"); emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.DecPre: ~~~~~~~~ @@ -1216,7 +1216,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("--"); emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Throw: ~~~~~~~~ @@ -1224,7 +1224,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("throw "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(";"); break; case NodeType.Typeof: @@ -1233,7 +1233,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("typeof "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Delete: ~~~~~~~~ @@ -1241,7 +1241,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("delete "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Void: ~~~~~~~~ @@ -1249,14 +1249,14 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("void "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.TypeAssertion: ~~~~~~~~ !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; default: throw new Error("please implement in derived class"); @@ -1531,7 +1531,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error if (!emitter.tryEmitConstant(this)) { emitter.emitJavascript(this.operand1, TokenID.Dot, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput("."); emitter.emitJavascriptName(this.operand2, false); } @@ -1561,24 +1561,24 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand1, TokenID.Colon, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? } else { emitter.emitJavascript(this.operand1, TokenID.Colon, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutputTrimmable(": "); } emitter.emitJavascript(this.operand2, TokenID.Comma, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Comma: ~~~~~~~~ !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand1, TokenID.Comma, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? if (emitter.emitState.inObjectLiteral) { emitter.writeLineToOutput(", "); } @@ -1587,7 +1587,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand2, TokenID.Comma, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? break; case NodeType.Is: ~~~~~~~~ @@ -1626,15 +1626,15 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascript(this.operand1, TokenID.Question, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(" ? "); emitter.emitJavascript(this.operand2, TokenID.Question, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(" : "); emitter.emitJavascript(this.operand3, TokenID.Question, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -1799,7 +1799,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.firstModAlias = this.firstAliasedModToString(); emitter.emitJavascript(this.alias, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? // the dynamic import case will insert the semi-colon automatically if (!this.isDynamicImport) { emitter.writeToOutput(";"); @@ -2075,7 +2075,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error var context = new ControlFlowContext(entry, exit); ~~~~~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ControlFlowContext'. +!!! error TS2552: Cannot find name 'ControlFlowContext'. Did you mean 'controlFlowPrefix'? var controlFlowPrefix = (ast: AST, parent: AST, walker: IAstWalker) => { ~~~~~~~~~~ @@ -2321,7 +2321,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascriptList(this.bod, null, TokenID.Semicolon, true, false, false, true, this.requiresInherits); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -2506,7 +2506,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error super(nodeType); this.flags |= ASTFlags.IsStatement; ~~~~~~~~ -!!! error TS2304: Cannot find name 'ASTFlags'. +!!! error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? } public isLoop() { return false; } @@ -2593,7 +2593,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error if (this.statements) { emitter.emitJavascriptList(this.statements, null, TokenID.Semicolon, true, false, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? } if (this.isStatementBlock) { emitter.indenter.decreaseIndent(); @@ -2730,7 +2730,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("while("); emitter.emitJavascript(this.cond, TokenID.While, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(")"); emitter.emitJavascriptStatements(this.body, false, false); emitter.setInObjectLiteral(temp); @@ -2811,7 +2811,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput('('); emitter.emitJavascript(this.cond, TokenID.CloseParen, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(")"); emitter.setInObjectLiteral(temp); emitter.recordSourceMappingEnd(this); @@ -2884,7 +2884,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("if("); emitter.emitJavascript(this.cond, TokenID.If, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.emitJavascriptStatements(this.thenBod, true, false); @@ -2979,7 +2979,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("return "); emitter.emitJavascript(this.returnExpression, TokenID.Semicolon, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? } else { emitter.writeToOutput("return;"); @@ -3110,11 +3110,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("for("); emitter.emitJavascript(this.lval, TokenID.For, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(" in "); emitter.emitJavascript(this.obj, TokenID.For, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.emitJavascriptStatements(this.body, true, false); @@ -3198,23 +3198,23 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.init, TokenID.For, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? } else { emitter.setInVarBlock((this.init).members.length); emitter.emitJavascriptList(this.init, null, TokenID.For, false, false, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? } } emitter.writeToOutput("; "); emitter.emitJavascript(this.cond, TokenID.For, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput("; "); emitter.emitJavascript(this.incr, TokenID.For, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(")"); emitter.emitJavascriptStatements(this.body, true, false); emitter.setInObjectLiteral(temp); @@ -3328,7 +3328,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error if (this.expr) { emitter.emitJavascript(this.expr, TokenID.With, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? } emitter.writeToOutput(")"); @@ -3369,7 +3369,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("switch("); emitter.emitJavascript(this.val, TokenID.Identifier, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.writeLineToOutput(" {"); @@ -3379,7 +3379,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error var caseExpr = this.caseList.members[i]; emitter.emitJavascript(caseExpr, TokenID.Case, true); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeLineToOutput(""); } emitter.indenter.decreaseIndent(); @@ -3459,7 +3459,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("case "); emitter.emitJavascript(this.expr, TokenID.Identifier, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? } else { emitter.writeToOutput("default"); @@ -3532,7 +3532,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error typeFlow.inTypeRefTypeCheck = true; var typeLink = getTypeLink(this, typeFlow.checker, true); ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'getTypeLink'. +!!! error TS2552: Cannot find name 'getTypeLink'. Did you mean 'typeLink'? typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); if (this.term) { @@ -3570,10 +3570,10 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascript(this.tryNode, TokenID.Try, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.emitJavascript(this.finallyNode, TokenID.Finally, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); } @@ -3591,11 +3591,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'ControlFlowContext'. var afterFinally = new BasicBlock(); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'BasicBlock'. +!!! error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? context.walk(this.tryNode, this); var finBlock = new BasicBlock(); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'BasicBlock'. +!!! error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? if (context.current) { context.current.addSuccessor(finBlock); } @@ -3634,10 +3634,10 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascript(this.tryNode, TokenID.Try, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.emitJavascript(this.catchNode, TokenID.Catch, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -3703,7 +3703,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("try "); emitter.emitJavascript(this.body, TokenID.Try, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -3754,12 +3754,12 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("catch ("); emitter.emitJavascript(this.param, TokenID.OpenParen, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.emitJavascript(this.body, TokenID.Catch, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -3771,7 +3771,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error context.addContent(this.param); var bodBlock = new BasicBlock(); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'BasicBlock'. +!!! error TS2552: Cannot find name 'BasicBlock'. Did you mean 'bodBlock'? context.current.addSuccessor(bodBlock); context.current = bodBlock; } @@ -3790,7 +3790,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error this.param = typeFlow.typeCheck(this.param); var exceptVar = new ValueLocation(); ~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ValueLocation'. +!!! error TS2552: Cannot find name 'ValueLocation'. Did you mean 'LocationInfo'? var varSym = new VariableSymbol((this.param).id.text, ~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'VariableSymbol'. @@ -3846,7 +3846,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("finally"); emitter.emitJavascript(this.body, TokenID.Finally, false); ~~~~~~~ -!!! error TS2304: Cannot find name 'TokenID'. +!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } diff --git a/tests/baselines/reference/parserRealSource13.errors.txt b/tests/baselines/reference/parserRealSource13.errors.txt index 6ddc41ed610..ddf67bb6dad 100644 --- a/tests/baselines/reference/parserRealSource13.errors.txt +++ b/tests/baselines/reference/parserRealSource13.errors.txt @@ -113,7 +113,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(123,26): error tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(123,39): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(128,33): error TS2339: Property 'getAstWalkerFactory' does not exist on type 'typeof TypeScript'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(132,51): error TS2304: Cannot find name 'AST'. -tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error TS2304: Cannot find name 'NodeType'. +tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error TS2552: Cannot find name 'NodeType'. Did you mean 'nodeType'? ==== tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts (116 errors) ==== @@ -483,7 +483,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error var nodeType = ast.nodeType; var callbackString = (NodeType)._map[nodeType] + "Callback"; ~~~~~~~~ -!!! error TS2304: Cannot find name 'NodeType'. +!!! error TS2552: Cannot find name 'NodeType'. Did you mean 'nodeType'? if (callback[callbackString]) { return callback[callbackString](pre, ast); } diff --git a/tests/baselines/reference/parserRealSource7.errors.txt b/tests/baselines/reference/parserRealSource7.errors.txt index a3635dabc48..cbe09f8e708 100644 --- a/tests/baselines/reference/parserRealSource7.errors.txt +++ b/tests/baselines/reference/parserRealSource7.errors.txt @@ -1,9 +1,9 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(12,38): error TS2304: Cannot find name 'ASTList'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(12,62): error TS2304: Cannot find name 'TypeLink'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(16,37): error TS2304: Cannot find name 'TypeLink'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(16,37): error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(16,45): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(21,36): error TS2304: Cannot find name 'TypeLink'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(21,36): error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(29,29): error TS2304: Cannot find name 'Type'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(29,45): error TS2304: Cannot find name 'TypeDeclaration'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(34,43): error TS2304: Cannot find name 'Type'. @@ -11,11 +11,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(34,54): error TS tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(34,68): error TS2304: Cannot find name 'TypeCollectionContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(35,25): error TS2304: Cannot find name 'ValueLocation'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(36,30): error TS2304: Cannot find name 'TypeLink'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(41,17): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(41,17): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(43,31): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(43,54): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(49,58): error TS2304: Cannot find name 'Type'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(50,29): error TS2304: Cannot find name 'Signature'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(50,29): error TS2552: Cannot find name 'Signature'. Did you mean 'signature'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(51,36): error TS2304: Cannot find name 'TypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(55,30): error TS2304: Cannot find name 'SignatureGroup'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(59,66): error TS2304: Cannot find name 'Type'. @@ -46,18 +46,18 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(154,27): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(155,26): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(155,55): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(165,28): error TS2304: Cannot find name 'ModuleType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(169,26): error TS2304: Cannot find name 'TypeSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(169,26): error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(186,48): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(186,61): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(186,75): error TS2304: Cannot find name 'TypeCollectionContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(189,25): error TS2304: Cannot find name 'ModuleDeclaration'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(189,46): error TS2304: Cannot find name 'ModuleDeclaration'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(191,25): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(191,54): error TS2304: Cannot find name 'ModuleFlags'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(191,54): error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(192,22): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(192,51): error TS2304: Cannot find name 'ModuleFlags'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(192,51): error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(194,26): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(194,55): error TS2304: Cannot find name 'ModuleFlags'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(194,55): error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(195,25): error TS2304: Cannot find name 'Identifier'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(197,25): error TS2304: Cannot find name 'isQuoted'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(200,25): error TS2304: Cannot find name 'TypeSymbol'. @@ -71,7 +71,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,48): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,66): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,90): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,113): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(207,31): error TS2304: Cannot find name 'ModuleType'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(207,31): error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(209,42): error TS2304: Cannot find name 'TypeFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(211,39): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(211,57): error TS2304: Cannot find name 'DualStringHashTable'. @@ -81,8 +81,8 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,46): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,64): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,88): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(212,111): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(216,30): error TS2304: Cannot find name 'TypeSymbol'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(231,72): error TS2304: Cannot find name 'NodeType'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(216,30): error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(231,72): error TS2552: Cannot find name 'NodeType'. Did you mean 'modType'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(234,27): error TS2304: Cannot find name 'TypeSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(238,80): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(239,37): error TS2304: Cannot find name 'ScopedMembers'. @@ -100,7 +100,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(250,82): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(251,38): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(251,56): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(251,107): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(253,27): error TS2304: Cannot find name 'ModuleType'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(253,27): error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(255,38): error TS2304: Cannot find name 'TypeFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(272,33): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(276,33): error TS2304: Cannot find name 'SymbolFlags'. @@ -142,7 +142,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,47): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,65): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,89): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(349,112): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(350,30): error TS2304: Cannot find name 'TypeSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(350,30): error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(360,37): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(364,37): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(368,37): error TS2304: Cannot find name 'SymbolFlags'. @@ -196,7 +196,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(476,57): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(477,29): error TS2304: Cannot find name 'ValueLocation'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,29): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,55): error TS2304: Cannot find name 'VarFlags'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,34): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,60): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(492,30): error TS2304: Cannot find name 'getTypeLink'. @@ -218,7 +218,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,26): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,52): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(518,22): error TS2304: Cannot find name 'FieldSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(531,29): error TS2304: Cannot find name 'ValueLocation'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,53): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,75): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(539,38): error TS2304: Cannot find name 'SymbolFlags'. @@ -327,7 +327,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T if (baseTypeLinks == null) { baseTypeLinks = new TypeLink[]; ~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeLink'. +!!! error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. } @@ -336,7 +336,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var name = baseExpr; var typeLink = new TypeLink(); ~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeLink'. +!!! error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? typeLink.ast = name; baseTypeLinks[baseTypeLinks.length] = typeLink; } @@ -372,7 +372,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol("prototype", ast.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, true, field); fieldSymbol.flags |= (SymbolFlags.Property | SymbolFlags.BuiltIn); ~~~~~~~~~~~ @@ -389,7 +389,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T !!! error TS2304: Cannot find name 'Type'. var signature = new Signature(); ~~~~~~~~~ -!!! error TS2304: Cannot find name 'Signature'. +!!! error TS2552: Cannot find name 'Signature'. Did you mean 'signature'? signature.returnType = new TypeLink(); ~~~~~~~~ !!! error TS2304: Cannot find name 'TypeLink'. @@ -570,7 +570,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T typeSymbol = new TypeSymbol(importDecl.id.text, importDecl.minChar, ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeSymbol'. +!!! error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? context.checker.locationInfo.unitIndex, modType); typeSymbol.aliasLink = importDecl; @@ -606,18 +606,18 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ModuleFlags'. +!!! error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? var isEnum = hasFlag(moduleDecl.modFlags, ModuleFlags.IsEnum); ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ModuleFlags'. +!!! error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? var isGlobal = context.scopeChain.container == context.checker.gloMod; var isExported = hasFlag(moduleDecl.modFlags, ModuleFlags.Exported); ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ModuleFlags'. +!!! error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? var modName = (moduleDecl.name).text; ~~~~~~~~~~ !!! error TS2304: Cannot find name 'Identifier'. @@ -658,7 +658,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T !!! error TS2304: Cannot find name 'StringHashTable'. modType = new ModuleType(enclosedTypes, ambientEnclosedTypes); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ModuleType'. +!!! error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? if (isEnum) { modType.typeFlags |= TypeFlags.IsEnum; ~~~~~~~~~ @@ -687,7 +687,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T typeSymbol = new TypeSymbol(modName, moduleDecl.minChar, ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeSymbol'. +!!! error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? context.checker.locationInfo.unitIndex, modType); if (context.scopeChain.moduleDecl) { @@ -704,7 +704,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T else { if (symbol && symbol.declAST && symbol.declAST.nodeType != NodeType.ModuleDeclaration) { ~~~~~~~~ -!!! error TS2304: Cannot find name 'NodeType'. +!!! error TS2552: Cannot find name 'NodeType'. Did you mean 'modType'? context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); } typeSymbol = symbol; @@ -762,7 +762,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T modType = new ModuleType(enclosedTypes, ambientEnclosedTypes); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ModuleType'. +!!! error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? if (isEnum) { modType.typeFlags |= TypeFlags.IsEnum; ~~~~~~~~~ @@ -943,7 +943,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T !!! error TS2304: Cannot find name 'StringHashTable'. typeSymbol = new TypeSymbol(className, classDecl.minChar, ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeSymbol'. +!!! error TS2552: Cannot find name 'TypeSymbol'. Did you mean 'typeSymbol'? context.checker.locationInfo.unitIndex, classType); typeSymbol.declAST = classDecl; typeSymbol.instanceType = instanceType; @@ -1181,7 +1181,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(argDecl.id.text, argDecl.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, !hasFlag(argDecl.varFlags, VarFlags.Readonly), ~~~~~~~ @@ -1278,7 +1278,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(varDecl.id.text, varDecl.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, (varDecl.varFlags & VarFlags.Readonly) == VarFlags.None, ~~~~~~~~ diff --git a/tests/baselines/reference/parserRealSource8.errors.txt b/tests/baselines/reference/parserRealSource8.errors.txt index 6249d3fd991..d4d26e5489f 100644 --- a/tests/baselines/reference/parserRealSource8.errors.txt +++ b/tests/baselines/reference/parserRealSource8.errors.txt @@ -47,7 +47,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(160,52): error T tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(160,76): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(160,99): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(162,28): error TS2304: Cannot find name 'Type'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(163,30): error TS2304: Cannot find name 'WithSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(163,30): error TS2552: Cannot find name 'WithSymbol'. Did you mean 'withSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(170,40): error TS2339: Property 'SymbolScopeBuilder' does not exist on type 'typeof TypeScript'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(176,50): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(177,25): error TS2304: Cannot find name 'FuncDecl'. @@ -74,19 +74,19 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(284,38): error T tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(286,55): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(292,43): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(309,29): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,31): error TS2304: Cannot find name 'ScopedMembers'. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,31): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,49): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,84): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(311,36): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,38): error TS2304: Cannot find name 'ScopedMembers'. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,38): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,56): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,98): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(313,35): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,37): error TS2304: Cannot find name 'ScopedMembers'. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,37): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,55): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,96): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(315,42): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,44): error TS2304: Cannot find name 'ScopedMembers'. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,44): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,62): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,110): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(321,26): error TS2304: Cannot find name 'SymbolScopeBuilder'. @@ -397,7 +397,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'Type'. var withSymbol = new WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'WithSymbol'. +!!! error TS2552: Cannot find name 'WithSymbol'. Did you mean 'withSymbol'? withType.members = members; withType.ambientMembers = ambientMembers; withType.symbol = withSymbol; @@ -598,7 +598,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var funcMembers = new ScopedMembers(new DualStringHashTable(funcTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ScopedMembers'. +!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ @@ -608,7 +608,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var ambientFuncMembers = new ScopedMembers(new DualStringHashTable(ambientFuncTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ScopedMembers'. +!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ @@ -618,7 +618,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var funcStaticMembers = new ScopedMembers(new DualStringHashTable(funcStaticTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ScopedMembers'. +!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ @@ -628,7 +628,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var ambientFuncStaticMembers = new ScopedMembers(new DualStringHashTable(ambientFuncStaticTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'ScopedMembers'. +!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt index ab0c1dc4d2e..cf1bd1fd2e2 100644 --- a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt +++ b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity1.ts(2,2): error TS2304: Cannot find name 'notregexp'. +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity1.ts(2,2): error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity1.ts(2,12): error TS2304: Cannot find name 'a'. @@ -6,6 +6,6 @@ tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpre 1 /notregexp/a.foo(); ~~~~~~~~~ -!!! error TS2304: Cannot find name 'notregexp'. +!!! error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? ~ !!! error TS2304: Cannot find name 'a'. \ No newline at end of file diff --git a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt index eac54ef0fe4..cfe5b118ee5 100644 --- a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt +++ b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts(1,6): error TS2304: Cannot find name 'notregexp'. +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts(1,6): error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts(1,16): error TS2304: Cannot find name 'a'. ==== tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts (2 errors) ==== (1) /notregexp/a.foo(); ~~~~~~~~~ -!!! error TS2304: Cannot find name 'notregexp'. +!!! error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? ~ !!! error TS2304: Cannot find name 'a'. \ No newline at end of file diff --git a/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt b/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt index c86756b4ab1..3d35062bfc2 100644 --- a/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt +++ b/tests/baselines/reference/parserS7.2_A1.5_T2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts (2 errors) ==== @@ -18,7 +18,7 @@ tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS if (x !== 1) { $ERROR('#1: eval("\\u00A0var x\\u00A0= 1\\u00A0"); x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } //CHECK#2 @@ -26,7 +26,7 @@ tests/cases/conformance/parser/ecmascript5/parserS7.2_A1.5_T2.ts(20,3): error TS if (x !== 1) { $ERROR('#2:  var x = 1 ; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } diff --git a/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt b/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt index e999066aa41..d4131cc799d 100644 --- a/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt +++ b/tests/baselines/reference/parserS7.3_A1.1_T2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts(17,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts(17,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts (1 errors) ==== @@ -20,7 +20,7 @@ tests/cases/conformance/parser/ecmascript5/parserS7.3_A1.1_T2.ts(17,3): error TS if (x !== 1) { $ERROR('#1: var\\nx\\n=\\n1\\n; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt b/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt index 153fb96ddac..c63ee2056b7 100644 --- a/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt +++ b/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt @@ -1,36 +1,36 @@ -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(18,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(22,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(26,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(30,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(34,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(38,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(42,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(46,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(50,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(54,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(58,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(62,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(66,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(70,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(74,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(78,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(82,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(86,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(90,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(94,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(98,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(102,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(106,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(110,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(114,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(118,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(122,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(126,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(130,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(134,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(138,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(142,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(18,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(22,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(26,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(30,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(34,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(38,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(42,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(46,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(50,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(54,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(58,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(62,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(66,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(70,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(74,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(78,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(82,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(86,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(90,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(94,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(98,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(102,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(106,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(110,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(114,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(118,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(122,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(126,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(130,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(134,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(138,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(142,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts (33 errors) ==== @@ -49,199 +49,199 @@ tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(142,3): error T if (А !== 1) { $ERROR('#А'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0411 = 1; if (Б !== 1) { $ERROR('#Б'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0412 = 1; if (В !== 1) { $ERROR('#В'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0413 = 1; if (Г !== 1) { $ERROR('#Г'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0414 = 1; if (Д !== 1) { $ERROR('#Д'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0415 = 1; if (Е !== 1) { $ERROR('#Е'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0416 = 1; if (Ж !== 1) { $ERROR('#Ж'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0417 = 1; if (З !== 1) { $ERROR('#З'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0418 = 1; if (И !== 1) { $ERROR('#И'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0419 = 1; if (Й !== 1) { $ERROR('#Й'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041A = 1; if (К !== 1) { $ERROR('#К'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041B = 1; if (Л !== 1) { $ERROR('#Л'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041C = 1; if (М !== 1) { $ERROR('#М'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041D = 1; if (Н !== 1) { $ERROR('#Н'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041E = 1; if (О !== 1) { $ERROR('#О'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041F = 1; if (П !== 1) { $ERROR('#П'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0420 = 1; if (Р !== 1) { $ERROR('#Р'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0421 = 1; if (С !== 1) { $ERROR('#С'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0422 = 1; if (Т !== 1) { $ERROR('#Т'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0423 = 1; if (У !== 1) { $ERROR('#У'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0424 = 1; if (Ф !== 1) { $ERROR('#Ф'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0425 = 1; if (Х !== 1) { $ERROR('#Х'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0426 = 1; if (Ц !== 1) { $ERROR('#Ц'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0427 = 1; if (Ч !== 1) { $ERROR('#Ч'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0428 = 1; if (Ш !== 1) { $ERROR('#Ш'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0429 = 1; if (Щ !== 1) { $ERROR('#Щ'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042A = 1; if (Ъ !== 1) { $ERROR('#Ъ'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042B = 1; if (Ы !== 1) { $ERROR('#Ы'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042C = 1; if (Ь !== 1) { $ERROR('#Ь'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042D = 1; if (Э !== 1) { $ERROR('#Э'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042E = 1; if (Ю !== 1) { $ERROR('#Ю'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042F = 1; if (Я !== 1) { $ERROR('#Я'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0401 = 1; if (Ё !== 1) { $ERROR('#Ё'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/parserSkippedTokens16.errors.txt b/tests/baselines/reference/parserSkippedTokens16.errors.txt index fc3565e9786..3f0321ed00c 100644 --- a/tests/baselines/reference/parserSkippedTokens16.errors.txt +++ b/tests/baselines/reference/parserSkippedTokens16.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,1): error TS2304: Cannot find name 'foo'. +tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,1): error TS2552: Cannot find name 'foo'. Did you mean 'Foo'? tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,6): error TS1005: ';' expected. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,8): error TS2304: Cannot find name 'Bar'. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,12): error TS1005: ';' expected. @@ -11,7 +11,7 @@ tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.t ==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts (8 errors) ==== foo(): Bar { } ~~~ -!!! error TS2304: Cannot find name 'foo'. +!!! error TS2552: Cannot find name 'foo'. Did you mean 'Foo'? ~ !!! error TS1005: ';' expected. ~~~ diff --git a/tests/baselines/reference/parserSymbolIndexer5.errors.txt b/tests/baselines/reference/parserSymbolIndexer5.errors.txt index a8c19338e01..7906d08912c 100644 --- a/tests/baselines/reference/parserSymbolIndexer5.errors.txt +++ b/tests/baselines/reference/parserSymbolIndexer5.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,6): error TS2304: Cannot find name 's'. tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,7): error TS1005: ']' expected. -tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,9): error TS2304: Cannot find name 'symbol'. +tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,9): error TS2552: Cannot find name 'symbol'. Did you mean 'Symbol'? tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,15): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(2,16): error TS1136: Property assignment expected. tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(3,1): error TS1005: ':' expected. @@ -14,7 +14,7 @@ tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer5.ts(3,1): ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'symbol'. +!!! error TS2552: Cannot find name 'symbol'. Did you mean 'Symbol'? ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/parserUnicode1.errors.txt b/tests/baselines/reference/parserUnicode1.errors.txt index 6f56522c05c..d04e136a534 100644 --- a/tests/baselines/reference/parserUnicode1.errors.txt +++ b/tests/baselines/reference/parserUnicode1.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(6,5): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(10,5): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(6,5): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(10,5): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts (2 errors) ==== @@ -10,12 +10,12 @@ tests/cases/conformance/parser/ecmascript5/parserUnicode1.ts(10,5): error TS2304 $ERROR('#6.1: var \\u0078x = 1; xx === 6. Actual: ' + (xx)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } } catch (e) { $ERROR('#6.2: var \\u0078x = 1; xx === 6. Actual: ' + (xx)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt index a2be22d5ee0..dde7576bfc4 100644 --- a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt +++ b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt @@ -4,12 +4,12 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,9): error TS2304: Cannot find name 'assign'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,16): error TS2304: Cannot find name 'context'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,23): error TS1005: ',' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,25): error TS2304: Cannot find name 'any'. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,30): error TS2304: Cannot find name 'value'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,25): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,30): error TS2552: Cannot find name 'value'. Did you mean 'eval'? tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,35): error TS1005: ',' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,37): error TS2304: Cannot find name 'any'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,37): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,41): error TS1005: ';' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,43): error TS2304: Cannot find name 'any'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,43): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,23): error TS2304: Cannot find name 'IPromise'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,45): error TS2304: Cannot find name 'IPromise'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,54): error TS1005: '>' expected. @@ -33,17 +33,17 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener ~ !!! error TS1005: ',' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? ~~~~~ -!!! error TS2304: Cannot find name 'value'. +!!! error TS2552: Cannot find name 'value'. Did you mean 'eval'? ~ !!! error TS1005: ',' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? } interface IQService { diff --git a/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt b/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt index 8d9acd6fb57..db5bd15b155 100644 --- a/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt +++ b/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Statements/BreakStatements/parser_breakInIterationOrSwitchStatement4.ts(1,15): error TS2304: Cannot find name 'something'. +tests/cases/conformance/parser/ecmascript5/Statements/BreakStatements/parser_breakInIterationOrSwitchStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? ==== tests/cases/conformance/parser/ecmascript5/Statements/BreakStatements/parser_breakInIterationOrSwitchStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2304: Cannot find name 'something'. +!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? break; } \ No newline at end of file diff --git a/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt b/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt index 5d87d3e3c71..4036de0d2a2 100644 --- a/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt +++ b/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Statements/ContinueStatements/parser_continueInIterationStatement4.ts(1,15): error TS2304: Cannot find name 'something'. +tests/cases/conformance/parser/ecmascript5/Statements/ContinueStatements/parser_continueInIterationStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? ==== tests/cases/conformance/parser/ecmascript5/Statements/ContinueStatements/parser_continueInIterationStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2304: Cannot find name 'something'. +!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? continue; } \ No newline at end of file diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index d3d0c4056a1..fc8d1c5a322 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -16,64 +16,64 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(691,50): e tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(716,47): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(721,62): error TS2304: Cannot find name 'ITextWriter'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(724,29): error TS2304: Cannot find name 'ITextWriter'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(754,53): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(754,53): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(764,56): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(765,37): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(767,47): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,13): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,42): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(765,37): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(767,47): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,13): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,42): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(781,23): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(794,49): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(795,49): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(794,49): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(795,49): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,115): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(999,40): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1041,43): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1044,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1045,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1046,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1047,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1048,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1049,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1050,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1051,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1052,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1053,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1055,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1058,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1044,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1045,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1046,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1047,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1048,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1049,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1050,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1051,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1052,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1053,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1055,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1058,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1059,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1061,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1064,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1061,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1064,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1065,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1067,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1070,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1067,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1070,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1071,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1073,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1073,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1074,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1076,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1076,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1077,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1079,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1079,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,35): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,74): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1107,173): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1176,132): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1193,29): error TS2304: Cannot find name 'WScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1193,29): error TS2552: Cannot find name 'WScript'. Did you mean 'scripts'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1256,126): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1257,25): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1263,31): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1280,45): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1280,45): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,124): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,209): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,142): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,227): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1302,43): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1304,39): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1307,38): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1311,45): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1321,21): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1302,43): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1304,39): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1307,38): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1311,45): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1321,21): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1340,38): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1344,165): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1345,26): error TS2503: Cannot find namespace 'TypeScript'. @@ -85,21 +85,21 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1461,23): tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1466,36): error TS2304: Cannot find name 'optionRegex'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1484,21): error TS2304: Cannot find name 'optionRegex'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1548,57): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1571,32): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1571,32): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1582,59): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1591,24): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1600,24): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1591,24): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1600,24): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1604,42): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1605,21): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1705,38): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1706,26): error TS2304: Cannot find name 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,62): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,87): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1714,30): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1724,34): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1739,20): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1714,30): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1724,34): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1739,20): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1746,80): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1750,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1750,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1758,84): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1769,51): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,39): error TS2503: Cannot find namespace 'Services'. @@ -107,7 +107,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,61): tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1785,25): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,38): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,68): error TS2503: Cannot find namespace 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): error TS2304: Cannot find name 'Diff'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): error TS2552: Cannot find name 'Diff'. Did you mean 'diff'? ==== tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts (110 errors) ==== @@ -902,7 +902,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var libFolder: string = global['WScript'] ? TypeScript.filePath(global['WScript'].ScriptFullName) : (__dirname + '/'); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? export var libText = IO ? IO.readFile(libFolder + "lib.d.ts") : ''; var stdout = new EmitterIOHost(); @@ -917,11 +917,11 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2503: Cannot find namespace 'TypeScript'. var compiler = c || new TypeScript.TypeScriptCompiler(stderr); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.parser.errorRecovery = true; compiler.settings.codeGenTarget = TypeScript.CodeGenTarget.ES5; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.settings.controlFlow = true; compiler.settings.controlFlowUseDef = true; if (Harness.usePull) { @@ -932,9 +932,9 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): compiler.parseEmitOption(stdout); TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.addUnit(Harness.Compiler.libText, "lib.d.ts", true); return compiler; } @@ -956,10 +956,10 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // requires unit to already exist in the compiler compiler.pullUpdateUnit(new TypeScript.StringSourceText(""), filename, true); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? compiler.pullUpdateUnit(new TypeScript.StringSourceText(code), filename, true); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } } else { @@ -1153,16 +1153,16 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var script = compiler.scripts.members[m]; var enclosingScopeContext = TypeScript.findEnclosingScopeAt(new TypeScript.NullLogger(), script, new TypeScript.StringSourceText(code), 0, false); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? var entries = new TypeScript.ScopeTraversal(compiler).getScopeEntries(enclosingScopeContext); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? for (var i = 0; i < entries.length; i++) { if (entries[i].name === targetIdentifier) { @@ -1224,88 +1224,88 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): switch (ast.nodeType) { case TypeScript.NodeType.Name: // Type Name? ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.Null: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.List: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.Empty: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.EmptyExpr: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.Asg: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.True: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.False: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.ArrayLit: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? case TypeScript.NodeType.TypeRef: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? break; case TypeScript.NodeType.Super: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = (ast).text; break; case TypeScript.NodeType.Regex: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = (ast).text; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.QString: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = (ast).text; break; case TypeScript.NodeType.NumberLit: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = (ast).text; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.Return: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? //name = (tyInfo.ast).returnExpression.actualText; // why is this complaining? break; case TypeScript.NodeType.InterfaceDeclaration: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = (ast).name.actualText; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.ModuleDeclaration: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = (ast).name.actualText; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.ClassDeclaration: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = (ast).name.actualText; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.FuncDecl: ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? name = !(ast).name ? "" : (ast).name.actualText; // name == null for lambdas ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. @@ -1429,7 +1429,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): else { WScript.Echo("non-match on: " + errorLines[i]); ~~~~~~~ -!!! error TS2304: Cannot find name 'WScript'. +!!! error TS2552: Cannot find name 'WScript'. Did you mean 'scripts'? } } } @@ -1524,7 +1524,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): if (Harness.usePull) { compiler.pullUpdateUnit(new TypeScript.StringSourceText(code), unitName, setRecovery); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } else { compiler.updateUnit(code, unitName, setRecovery); } @@ -1556,22 +1556,22 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var oldCompilerSettings = new TypeScript.CompilationSettings(); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? clone(compiler.settings, oldCompilerSettings); var oldEmitSettings = new TypeScript.EmitOptions(compiler.settings); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? clone(compiler.emitSettings, oldEmitSettings); var oldModuleGenTarget = TypeScript.moduleGenTarget; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? if (settingsCallback) { settingsCallback(compiler.settings); compiler.emitSettings = new TypeScript.EmitOptions(compiler.settings); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } try { compileString(code, filename, callback, context, references); @@ -1583,7 +1583,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): compiler.emitSettings = oldEmitSettings; TypeScript.moduleGenTarget = oldModuleGenTarget; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } } } @@ -1857,7 +1857,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): length: this.content.length, editRange: new TypeScript.ScriptEditRange(minChar, limChar, (limChar - minChar) + newText.length) ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? }); if (this.editRanges.length > this.maxScriptVersions) { @@ -1881,7 +1881,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // Too far away from what we know return TypeScript.ScriptEditRange.unknown(); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } var entries = this.editRanges.slice(initialEditRangeIndex); @@ -1892,7 +1892,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): return new TypeScript.ScriptEditRange(minDistFromStart, entries[0].length - minDistFromEnd, aggDelta); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } } @@ -2020,7 +2020,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2503: Cannot find namespace 'TypeScript'. var parser = new TypeScript.Parser(); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? parser.setErrorRecovery(null); parser.errorCallback = (a, b, c, d) => { }; @@ -2032,7 +2032,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): public parseFile(fileName: string) { var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName)) ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? return this.parseSourceText(fileName, sourceText); } @@ -2049,7 +2049,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): return TypeScript.getPositionFromZeroBasedLineColumn(script, line - 1, col - 1); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? } /** @@ -2064,7 +2064,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var result = TypeScript.getZeroBasedLineColumnFromPosition(script, position); ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? assert.is(result.line >= 0); assert.is(result.col >= 0); @@ -2360,7 +2360,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // Append diff to the report var diff = new Diff.StringDiff(expected, actual); ~~~~ -!!! error TS2304: Cannot find name 'Diff'. +!!! error TS2552: Cannot find name 'Diff'. Did you mean 'diff'? var header = '

' + descriptionForDescribe + '

'; header += '

Left file: ' + actualFilename + '; Right file: ' + refFilename + '

'; var trailer = '
'; diff --git a/tests/baselines/reference/parserindenter.errors.txt b/tests/baselines/reference/parserindenter.errors.txt index 2f51281e7aa..997b56b7db9 100644 --- a/tests/baselines/reference/parserindenter.errors.txt +++ b/tests/baselines/reference/parserindenter.errors.txt @@ -57,7 +57,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(265,91): tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(266,34): error TS2304: Cannot find name 'IndentationInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(274,53): error TS2304: Cannot find name 'AuthorParseNodeKind'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(278,50): error TS2304: Cannot find name 'Span'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(279,28): error TS2304: Cannot find name 'ParseTree'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(279,28): error TS2552: Cannot find name 'ParseTree'. Did you mean 'parseInt'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(288,60): error TS2304: Cannot find name 'TokenSpan'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(288,77): error TS2304: Cannot find name 'ParseNode'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(288,89): error TS2304: Cannot find name 'IndentationInfo'. @@ -527,7 +527,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): !!! error TS2304: Cannot find name 'Span'. node = ParseTree.FindCommonParentNode(semiColonStartSpan, semiColonStartSpan, node); ~~~~~~~~~ -!!! error TS2304: Cannot find name 'ParseTree'. +!!! error TS2552: Cannot find name 'ParseTree'. Did you mean 'parseInt'? indentationInfo = node.GetEffectiveChildrenIndentation(this); return indentationInfo; } diff --git a/tests/baselines/reference/primitiveTypeAssignment.errors.txt b/tests/baselines/reference/primitiveTypeAssignment.errors.txt index 3985a9acdc5..4048a00150f 100644 --- a/tests/baselines/reference/primitiveTypeAssignment.errors.txt +++ b/tests/baselines/reference/primitiveTypeAssignment.errors.txt @@ -1,18 +1,18 @@ -tests/cases/compiler/primitiveTypeAssignment.ts(1,9): error TS2304: Cannot find name 'any'. -tests/cases/compiler/primitiveTypeAssignment.ts(3,9): error TS2304: Cannot find name 'number'. -tests/cases/compiler/primitiveTypeAssignment.ts(5,9): error TS2304: Cannot find name 'boolean'. +tests/cases/compiler/primitiveTypeAssignment.ts(1,9): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/primitiveTypeAssignment.ts(3,9): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/compiler/primitiveTypeAssignment.ts(5,9): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? ==== tests/cases/compiler/primitiveTypeAssignment.ts (3 errors) ==== var x = any; ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? var y = number; ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? var z = boolean; ~~~~~~~ -!!! error TS2304: Cannot find name 'boolean'. +!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? \ No newline at end of file diff --git a/tests/baselines/reference/privateIndexer2.errors.txt b/tests/baselines/reference/privateIndexer2.errors.txt index 9f087b22379..a12da313ffa 100644 --- a/tests/baselines/reference/privateIndexer2.errors.txt +++ b/tests/baselines/reference/privateIndexer2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,15): error TS1005: ']' expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2304: Cannot find name 'string'. +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,23): error TS1005: ',' expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,24): error TS1136: Property assignment expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32): error TS1005: ':' expected. @@ -13,7 +13,7 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32) ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/propertyOrdering.errors.txt b/tests/baselines/reference/propertyOrdering.errors.txt index ded6ec01aff..f9f638f592d 100644 --- a/tests/baselines/reference/propertyOrdering.errors.txt +++ b/tests/baselines/reference/propertyOrdering.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/propertyOrdering.ts(6,23): error TS2304: Cannot find name 'store'. -tests/cases/compiler/propertyOrdering.ts(9,34): error TS2339: Property 'store' does not exist on type 'Foo'. +tests/cases/compiler/propertyOrdering.ts(9,34): error TS2551: Property 'store' does not exist on type 'Foo'. Did you mean '_store'? tests/cases/compiler/propertyOrdering.ts(16,25): error TS2339: Property '_store' does not exist on type 'Bar'. tests/cases/compiler/propertyOrdering.ts(20,14): error TS2339: Property '_store' does not exist on type 'Bar'. @@ -17,7 +17,7 @@ tests/cases/compiler/propertyOrdering.ts(20,14): error TS2339: Property '_store' public bar() { return this.store; } // should be an error ~~~~~ -!!! error TS2339: Property 'store' does not exist on type 'Foo'. +!!! error TS2551: Property 'store' does not exist on type 'Foo'. Did you mean '_store'? } diff --git a/tests/baselines/reference/propertySignatures.errors.txt b/tests/baselines/reference/propertySignatures.errors.txt index fd415334e74..60a393aef4d 100644 --- a/tests/baselines/reference/propertySignatures.errors.txt +++ b/tests/baselines/reference/propertySignatures.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/propertySignatures.ts(2,13): error TS2300: Duplicate identifier 'a'. tests/cases/compiler/propertySignatures.ts(2,23): error TS2300: Duplicate identifier 'a'. -tests/cases/compiler/propertySignatures.ts(14,12): error TS2304: Cannot find name 'foo'. +tests/cases/compiler/propertySignatures.ts(14,12): error TS2552: Cannot find name 'foo'. Did you mean 'foo1'? ==== tests/cases/compiler/propertySignatures.ts (3 errors) ==== @@ -23,7 +23,7 @@ tests/cases/compiler/propertySignatures.ts(14,12): error TS2304: Cannot find nam var foo4: { (): void; }; var test = foo(); ~~~ -!!! error TS2304: Cannot find name 'foo'. +!!! error TS2552: Cannot find name 'foo'. Did you mean 'foo1'? // Should be OK var foo5: {();}; diff --git a/tests/baselines/reference/scanner10.1.1-8gs.errors.txt b/tests/baselines/reference/scanner10.1.1-8gs.errors.txt index 6e75f195c26..f8b0c121ee0 100644 --- a/tests/baselines/reference/scanner10.1.1-8gs.errors.txt +++ b/tests/baselines/reference/scanner10.1.1-8gs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(16,7): error TS2304: Cannot find name 'NotEarlyError'. +tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(16,7): error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(17,1): error TS7027: Unreachable code detected. tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(17,5): error TS1212: Identifier expected. 'public' is a reserved word in strict mode. @@ -21,7 +21,7 @@ tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(17,5): error TS "use strict"; throw NotEarlyError; ~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'NotEarlyError'. +!!! error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? var public = 1; ~~~ !!! error TS7027: Unreachable code detected. diff --git a/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt b/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt index 94200267e62..97d580c9b4b 100644 --- a/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt +++ b/tests/baselines/reference/scannerS7.2_A1.5_T2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts (2 errors) ==== @@ -18,7 +18,7 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error if (x !== 1) { $ERROR('#1: eval("\\u00A0var x\\u00A0= 1\\u00A0"); x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } //CHECK#2 @@ -26,7 +26,7 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.2_A1.5_T2.ts(20,3): error if (x !== 1) { $ERROR('#2:  var x = 1 ; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } diff --git a/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt b/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt index 278e1d79621..186427f5de9 100644 --- a/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt +++ b/tests/baselines/reference/scannerS7.3_A1.1_T2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts(17,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts(17,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts (1 errors) ==== @@ -20,7 +20,7 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.3_A1.1_T2.ts(17,3): error if (x !== 1) { $ERROR('#1: var\\nx\\n=\\n1\\n; x === 1. Actual: ' + (x)); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt b/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt index 97925d67549..6d850d8567f 100644 --- a/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt +++ b/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt @@ -1,36 +1,36 @@ -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(14,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(18,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(22,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(26,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(30,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(34,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(38,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(42,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(46,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(50,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(54,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(58,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(62,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(66,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(70,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(74,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(78,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(82,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(86,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(90,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(94,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(98,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(102,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(106,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(110,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(114,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(118,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(122,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(126,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(130,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(134,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(138,3): error TS2304: Cannot find name '$ERROR'. -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(142,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(14,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(18,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(22,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(26,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(30,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(34,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(38,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(42,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(46,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(50,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(54,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(58,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(62,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(66,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(70,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(74,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(78,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(82,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(86,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(90,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(94,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(98,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(102,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(106,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(110,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(114,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(118,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(122,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(126,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(130,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(134,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(138,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(142,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? ==== tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts (33 errors) ==== @@ -49,199 +49,199 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(142,3): error if (А !== 1) { $ERROR('#А'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0411 = 1; if (Б !== 1) { $ERROR('#Б'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0412 = 1; if (В !== 1) { $ERROR('#В'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0413 = 1; if (Г !== 1) { $ERROR('#Г'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0414 = 1; if (Д !== 1) { $ERROR('#Д'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0415 = 1; if (Е !== 1) { $ERROR('#Е'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0416 = 1; if (Ж !== 1) { $ERROR('#Ж'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0417 = 1; if (З !== 1) { $ERROR('#З'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0418 = 1; if (И !== 1) { $ERROR('#И'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0419 = 1; if (Й !== 1) { $ERROR('#Й'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041A = 1; if (К !== 1) { $ERROR('#К'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041B = 1; if (Л !== 1) { $ERROR('#Л'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041C = 1; if (М !== 1) { $ERROR('#М'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041D = 1; if (Н !== 1) { $ERROR('#Н'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041E = 1; if (О !== 1) { $ERROR('#О'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u041F = 1; if (П !== 1) { $ERROR('#П'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0420 = 1; if (Р !== 1) { $ERROR('#Р'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0421 = 1; if (С !== 1) { $ERROR('#С'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0422 = 1; if (Т !== 1) { $ERROR('#Т'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0423 = 1; if (У !== 1) { $ERROR('#У'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0424 = 1; if (Ф !== 1) { $ERROR('#Ф'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0425 = 1; if (Х !== 1) { $ERROR('#Х'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0426 = 1; if (Ц !== 1) { $ERROR('#Ц'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0427 = 1; if (Ч !== 1) { $ERROR('#Ч'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0428 = 1; if (Ш !== 1) { $ERROR('#Ш'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0429 = 1; if (Щ !== 1) { $ERROR('#Щ'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042A = 1; if (Ъ !== 1) { $ERROR('#Ъ'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042B = 1; if (Ы !== 1) { $ERROR('#Ы'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042C = 1; if (Ь !== 1) { $ERROR('#Ь'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042D = 1; if (Э !== 1) { $ERROR('#Э'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042E = 1; if (Ю !== 1) { $ERROR('#Ю'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u042F = 1; if (Я !== 1) { $ERROR('#Я'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } var \u0401 = 1; if (Ё !== 1) { $ERROR('#Ё'); ~~~~~~ -!!! error TS2304: Cannot find name '$ERROR'. +!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? } \ No newline at end of file diff --git a/tests/baselines/reference/scannertest1.errors.txt b/tests/baselines/reference/scannertest1.errors.txt index fce2a0b292a..6a98346e001 100644 --- a/tests/baselines/reference/scannertest1.errors.txt +++ b/tests/baselines/reference/scannertest1.errors.txt @@ -1,19 +1,19 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(1,1): error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,21): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,47): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,21): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,47): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(9,16): error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,22): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,47): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,22): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,47): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,22): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,47): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,22): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,47): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(15,9): error TS2304: Cannot find name 'Debug'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(15,22): error TS2662: Cannot find name 'isHexDigit'. Did you mean the static member 'CharacterInfo.isHexDigit'? tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(16,16): error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(17,20): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,21): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,46): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(19,23): error TS2304: Cannot find name 'CharacterCodes'. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(17,20): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,21): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,46): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(19,23): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? ==== tests/cases/conformance/scanner/ecmascript5/scannertest1.ts (16 errors) ==== @@ -25,9 +25,9 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2304 public static isDecimalDigit(c: number): boolean { return c >= CharacterCodes._0 && c <= CharacterCodes._9; ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? } public static isHexDigit(c: number): boolean { @@ -36,14 +36,14 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2304 !!! error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? (c >= CharacterCodes.A && c <= CharacterCodes.F) || ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? (c >= CharacterCodes.a && c <= CharacterCodes.f); ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? } public static hexValue(c: number): number { @@ -57,18 +57,18 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2304 !!! error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? ? (c - CharacterCodes._0) ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? : (c >= CharacterCodes.A && c <= CharacterCodes.F) ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? ? c - CharacterCodes.A + 10 ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? : c - CharacterCodes.a + 10; ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'CharacterCodes'. +!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? } } diff --git a/tests/baselines/reference/staticsInAFunction.errors.txt b/tests/baselines/reference/staticsInAFunction.errors.txt index 48104fd52f4..46636037c97 100644 --- a/tests/baselines/reference/staticsInAFunction.errors.txt +++ b/tests/baselines/reference/staticsInAFunction.errors.txt @@ -5,12 +5,12 @@ tests/cases/compiler/staticsInAFunction.ts(3,4): error TS1128: Declaration or st tests/cases/compiler/staticsInAFunction.ts(3,11): error TS2304: Cannot find name 'test'. tests/cases/compiler/staticsInAFunction.ts(3,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(3,20): error TS1005: ',' expected. -tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2304: Cannot find name 'string'. +tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/staticsInAFunction.ts(4,4): error TS1128: Declaration or statement expected. tests/cases/compiler/staticsInAFunction.ts(4,11): error TS2304: Cannot find name 'test'. tests/cases/compiler/staticsInAFunction.ts(4,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(4,21): error TS1109: Expression expected. -tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2304: Cannot find name 'any'. +tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. @@ -33,7 +33,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? static test(name?:any){} ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -44,7 +44,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2304: Cannot find name 'any'. +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/strictModeReservedWord.errors.txt b/tests/baselines/reference/strictModeReservedWord.errors.txt index 5a6de7792b7..f2f74c81a93 100644 --- a/tests/baselines/reference/strictModeReservedWord.errors.txt +++ b/tests/baselines/reference/strictModeReservedWord.errors.txt @@ -38,7 +38,7 @@ tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS1212: Identifier tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS2503: Cannot find namespace 'interface'. tests/cases/compiler/strictModeReservedWord.ts(22,22): error TS1212: Identifier expected. 'package' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(22,30): error TS1212: Identifier expected. 'implements' is a reserved word in strict mode. -tests/cases/compiler/strictModeReservedWord.ts(23,5): error TS2304: Cannot find name 'ublic'. +tests/cases/compiler/strictModeReservedWord.ts(23,5): error TS2552: Cannot find name 'ublic'. Did you mean 'public'? tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS1212: Identifier expected. 'static' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. @@ -148,7 +148,7 @@ tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invok !!! error TS1212: Identifier expected. 'implements' is a reserved word in strict mode. ublic(); ~~~~~ -!!! error TS2304: Cannot find name 'ublic'. +!!! error TS2552: Cannot find name 'ublic'. Did you mean 'public'? static(); ~~~~~~ !!! error TS1212: Identifier expected. 'static' is a reserved word in strict mode. diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt index e88f4c1ca96..c136d3dd573 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt @@ -91,7 +91,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,30): e tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,32): error TS1138: Parameter declaration expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,39): error TS1005: ';' expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,40): error TS1128: Declaration or statement expected. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,42): error TS2304: Cannot find name 'number'. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,42): error TS2552: Cannot find name 'number'. Did you mean 'Number'? tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,49): error TS1005: ';' expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,1): error TS7027: Unreachable code detected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,29): error TS2304: Cannot find name 'm'. @@ -425,7 +425,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e ~ !!! error TS1128: Declaration or statement expected. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? ~ !!! error TS1005: ';' expected. diff --git a/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt b/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt index 0607a01a11c..d6d7b2f277a 100644 --- a/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt +++ b/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt @@ -1,13 +1,13 @@ tests/cases/conformance/jsx/file.tsx(10,8): error TS1003: Identifier expected. tests/cases/conformance/jsx/file.tsx(10,10): error TS1005: ';' expected. -tests/cases/conformance/jsx/file.tsx(10,10): error TS2304: Cannot find name 'data'. +tests/cases/conformance/jsx/file.tsx(10,10): error TS2552: Cannot find name 'data'. Did you mean 'Date'? tests/cases/conformance/jsx/file.tsx(10,15): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/jsx/file.tsx(10,18): error TS1005: ':' expected. tests/cases/conformance/jsx/file.tsx(10,21): error TS1109: Expression expected. tests/cases/conformance/jsx/file.tsx(10,22): error TS1109: Expression expected. tests/cases/conformance/jsx/file.tsx(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/jsx/file.tsx(11,8): error TS1003: Identifier expected. -tests/cases/conformance/jsx/file.tsx(11,9): error TS2304: Cannot find name 'data'. +tests/cases/conformance/jsx/file.tsx(11,9): error TS2552: Cannot find name 'data'. Did you mean 'Date'? tests/cases/conformance/jsx/file.tsx(11,13): error TS1005: ';' expected. tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular expression literal. @@ -28,7 +28,7 @@ tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular ~~~~ !!! error TS1005: ';' expected. ~~~~ -!!! error TS2304: Cannot find name 'data'. +!!! error TS2552: Cannot find name 'data'. Did you mean 'Date'? ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. ~ @@ -43,7 +43,7 @@ tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular ~ !!! error TS1003: Identifier expected. ~~~~ -!!! error TS2304: Cannot find name 'data'. +!!! error TS2552: Cannot find name 'data'. Did you mean 'Date'? ~ !!! error TS1005: ';' expected. diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index c840e016083..bfc42321505 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -11,7 +11,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,5): erro tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS1005: '>' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS1005: ')' expected. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS2304: Cannot find name 'string'. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,48): error TS1005: ';' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(45,2): error TS2322: Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. @@ -19,7 +19,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,32): err tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS1005: ')' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS1005: ';' expected. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS2304: Cannot find name 'string'. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): error TS1005: ';' expected. @@ -91,7 +91,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err ~~~~~~ !!! error TS1005: ')' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ';' expected. str = numOrStr; // Error, no narrowing occurred @@ -110,7 +110,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt index d50d86afa5e..1c57ec5cf68 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt +++ b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt @@ -2,7 +2,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(1,7): tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(14,5): error TS2322: Type '""' is not assignable to type 'boolean'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,55): error TS2304: Cannot find name 'x'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,57): error TS1144: '{' or ';' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,57): error TS2304: Cannot find name 'is'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,57): error TS2552: Cannot find name 'is'. Did you mean 'isB'? tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,60): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,62): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(21,33): error TS2304: Cannot find name 'x'. @@ -19,9 +19,9 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(41,56) Type 'number' is not assignable to type 'string'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(45,56): error TS2677: A type predicate's type must be assignable to its parameter's type. Type 'T[]' is not assignable to type 'string'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(59,7): error TS2339: Property 'propB' does not exist on type 'A'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(64,7): error TS2339: Property 'propB' does not exist on type 'A'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(69,7): error TS2339: Property 'propB' does not exist on type 'A'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(59,7): error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(64,7): error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(69,7): error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(74,46): error TS2345: Argument of type '(p1: any) => p1 is C' is not assignable to parameter of type '(p1: any) => p1 is B'. Type predicate 'p1 is C' is not assignable to 'p1 is B'. Type 'C' is not assignable to type 'B'. @@ -34,16 +34,16 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(84,1): tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(90,1): error TS2322: Type '(p1: any, p2: any, p3: any) => p1 is A' is not assignable to type '(p1: any, p2: any) => p1 is A'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,9): error TS2304: Cannot find name 'b'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,11): error TS1005: '=' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,11): error TS2304: Cannot find name 'is'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,11): error TS2552: Cannot find name 'is'. Did you mean 'isB'? tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,14): error TS1005: ',' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,14): error TS2300: Duplicate identifier 'A'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,16): error TS2304: Cannot find name 'b'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,18): error TS1005: '=' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,18): error TS2304: Cannot find name 'is'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,18): error TS2552: Cannot find name 'is'. Did you mean 'isB'? tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,21): error TS1005: ',' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,20): error TS2304: Cannot find name 'b'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,22): error TS1144: '{' or ';' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,22): error TS2304: Cannot find name 'is'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,22): error TS2552: Cannot find name 'is'. Did you mean 'isB'? tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,25): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,27): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(103,25): error TS1228: A type predicate is only allowed in return type position for functions and methods. @@ -55,7 +55,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(110,9) tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(115,18): error TS1228: A type predicate is only allowed in return type position for functions and methods. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,22): error TS2304: Cannot find name 'p1'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,25): error TS1005: ';' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,25): error TS2304: Cannot find name 'is'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,25): error TS2552: Cannot find name 'is'. Did you mean 'isB'? tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,28): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(120,1): error TS1128: Declaration or statement expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(123,20): error TS1229: A type predicate cannot reference a rest parameter. @@ -91,7 +91,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1144: '{' or ';' expected. ~~ -!!! error TS2304: Cannot find name 'is'. +!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? ~ !!! error TS1005: ';' expected. ~ @@ -163,21 +163,21 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 if (isB(b)) { a.propB; ~~~~~ -!!! error TS2339: Property 'propB' does not exist on type 'A'. +!!! error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? } // Parameter index and argument index for the type guard target is not matching. if (funA(0, a)) { a.propB; // Error ~~~~~ -!!! error TS2339: Property 'propB' does not exist on type 'A'. +!!! error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? } // No type guard in if statement if (hasNoTypeGuard(a)) { a.propB; ~~~~~ -!!! error TS2339: Property 'propB' does not exist on type 'A'. +!!! error TS2551: Property 'propB' does not exist on type 'A'. Did you mean 'propA'? } // Type predicate type is not assignable @@ -223,7 +223,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1005: '=' expected. ~~ -!!! error TS2304: Cannot find name 'is'. +!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? ~ !!! error TS1005: ',' expected. ~ @@ -234,7 +234,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1005: '=' expected. ~~ -!!! error TS2304: Cannot find name 'is'. +!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? ~ !!! error TS1005: ',' expected. function b3(): A | b is A { @@ -243,7 +243,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1144: '{' or ';' expected. ~~ -!!! error TS2304: Cannot find name 'is'. +!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? ~ !!! error TS1005: ';' expected. ~ @@ -289,7 +289,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1005: ';' expected. ~~ -!!! error TS2304: Cannot find name 'is'. +!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt index 31db51bf57e..096b19c3717 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt @@ -3,14 +3,14 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(33,5): error TS2322: Type '"str"' is not assignable to type 'number'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(34,10): error TS2339: Property 'bar' does not exist on type 'B'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(41,10): error TS2339: Property 'bar' does not exist on type 'B'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(66,10): error TS2339: Property 'bar2' does not exist on type 'C1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(66,10): error TS2551: Property 'bar2' does not exist on type 'C1'. Did you mean 'bar1'? tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(72,10): error TS2339: Property 'bar1' does not exist on type 'C1 | C2'. Property 'bar1' does not exist on type 'C2'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(73,10): error TS2339: Property 'bar2' does not exist on type 'C1 | C2'. Property 'bar2' does not exist on type 'C1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(85,10): error TS2339: Property 'bar' does not exist on type 'D'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(91,10): error TS2339: Property 'bar' does not exist on type 'D'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(112,10): error TS2339: Property 'bar2' does not exist on type 'E1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(112,10): error TS2551: Property 'bar2' does not exist on type 'E1'. Did you mean 'bar1'? tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(118,11): error TS2339: Property 'bar1' does not exist on type 'E1 | E2'. Property 'bar1' does not exist on type 'E2'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(119,11): error TS2339: Property 'bar2' does not exist on type 'E1 | E2'. @@ -19,11 +19,11 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru Property 'foo' does not exist on type 'string'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(135,11): error TS2339: Property 'bar' does not exist on type 'string | F'. Property 'bar' does not exist on type 'string'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(160,11): error TS2339: Property 'foo2' does not exist on type 'G1'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(166,11): error TS2339: Property 'foo2' does not exist on type 'G1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(160,11): error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(166,11): error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(182,11): error TS2339: Property 'bar' does not exist on type 'H'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(187,11): error TS2339: Property 'foo1' does not exist on type 'H'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(188,11): error TS2339: Property 'foo2' does not exist on type 'H'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(187,11): error TS2551: Property 'foo1' does not exist on type 'H'. Did you mean 'foo'? +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(188,11): error TS2551: Property 'foo2' does not exist on type 'H'. Did you mean 'foo'? ==== tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts (20 errors) ==== @@ -104,7 +104,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj5.bar1; obj5.bar2; ~~~~ -!!! error TS2339: Property 'bar2' does not exist on type 'C1'. +!!! error TS2551: Property 'bar2' does not exist on type 'C1'. Did you mean 'bar1'? } var obj6: any; @@ -162,7 +162,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj9.bar1; obj9.bar2; ~~~~ -!!! error TS2339: Property 'bar2' does not exist on type 'E1'. +!!! error TS2551: Property 'bar2' does not exist on type 'E1'. Did you mean 'bar1'? } var obj10: any; @@ -224,7 +224,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj13.foo1; obj13.foo2; ~~~~ -!!! error TS2339: Property 'foo2' does not exist on type 'G1'. +!!! error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? } var obj14: any; @@ -232,7 +232,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj14.foo1; obj14.foo2; ~~~~ -!!! error TS2339: Property 'foo2' does not exist on type 'G1'. +!!! error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? } // a type with a prototype that has any type @@ -257,10 +257,10 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru if (obj16 instanceof H) { obj16.foo1; ~~~~ -!!! error TS2339: Property 'foo1' does not exist on type 'H'. +!!! error TS2551: Property 'foo1' does not exist on type 'H'. Did you mean 'foo'? obj16.foo2; ~~~~ -!!! error TS2339: Property 'foo2' does not exist on type 'H'. +!!! error TS2551: Property 'foo2' does not exist on type 'H'. Did you mean 'foo'? } var obj17: any; diff --git a/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt b/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt index 872a0a10923..f01f7520cba 100644 --- a/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt +++ b/tests/baselines/reference/typeParametersAndParametersInComputedNames.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,10): error TS2304: Cannot find name 'T'. -tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,13): error TS2304: Cannot find name 'a'. +tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,13): error TS2552: Cannot find name 'a'. Did you mean 'A'? ==== tests/cases/compiler/typeParametersAndParametersInComputedNames.ts (2 errors) ==== @@ -12,6 +12,6 @@ tests/cases/compiler/typeParametersAndParametersInComputedNames.ts(6,13): error ~ !!! error TS2304: Cannot find name 'T'. ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS2552: Cannot find name 'a'. Did you mean 'A'? } } \ No newline at end of file diff --git a/tests/baselines/reference/undeclaredMethod.errors.txt b/tests/baselines/reference/undeclaredMethod.errors.txt index 942d1908182..4e7bf187440 100644 --- a/tests/baselines/reference/undeclaredMethod.errors.txt +++ b/tests/baselines/reference/undeclaredMethod.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/undeclaredMethod.ts(10,3): error TS2339: Property 'saltbar' does not exist on type 'C'. +tests/cases/compiler/undeclaredMethod.ts(10,3): error TS2551: Property 'saltbar' does not exist on type 'C'. Did you mean 'salt'? ==== tests/cases/compiler/undeclaredMethod.ts (1 errors) ==== @@ -13,6 +13,6 @@ tests/cases/compiler/undeclaredMethod.ts(10,3): error TS2339: Property 'saltbar' c.salt(); // cool c.saltbar(); // crash ~~~~~~~ -!!! error TS2339: Property 'saltbar' does not exist on type 'C'. +!!! error TS2551: Property 'saltbar' does not exist on type 'C'. Did you mean 'salt'? \ No newline at end of file diff --git a/tests/baselines/reference/undeclaredVarEmit.errors.txt b/tests/baselines/reference/undeclaredVarEmit.errors.txt index a95323aa362..689360aa899 100644 --- a/tests/baselines/reference/undeclaredVarEmit.errors.txt +++ b/tests/baselines/reference/undeclaredVarEmit.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/undeclaredVarEmit.ts(1,1): error TS7028: Unused label. -tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2304: Cannot find name 'number'. +tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2552: Cannot find name 'number'. Did you mean 'Number'? ==== tests/cases/compiler/undeclaredVarEmit.ts (2 errors) ==== @@ -7,4 +7,4 @@ tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2304: Cannot find name ' ~ !!! error TS7028: Unused label. ~~~~~~ -!!! error TS2304: Cannot find name 'number'. \ No newline at end of file +!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixAddMissingMember3.ts b/tests/cases/fourslash/codeFixAddMissingMember3.ts index 5864c9c1029..47cacd6753a 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember3.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember3.ts @@ -11,4 +11,4 @@ verify.rangeAfterCodeFix(`class C { static method() { this.foo = 10; } -}`); \ No newline at end of file +}`, /*includeWhiteSpace*/false, /*errorCode*/ undefined, /*index*/ 0); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport0.ts b/tests/cases/fourslash/importNameCodeFixExistingImport0.ts index 5e5be220688..e5b63499878 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport0.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport0.ts @@ -7,4 +7,4 @@ //// export function f1() {} //// export var v1 = 5; -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport1.ts b/tests/cases/fourslash/importNameCodeFixExistingImport1.ts index 9571d0fcf57..49680692b6c 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport1.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport1.ts @@ -8,4 +8,4 @@ //// export var v1 = 5; //// export default var d1 = 6; -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport10.ts b/tests/cases/fourslash/importNameCodeFixExistingImport10.ts index 8a178e72730..a9525d272da 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport10.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport10.ts @@ -18,4 +18,4 @@ verify.importFixAtPosition([ v2, f1 }` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport11.ts b/tests/cases/fourslash/importNameCodeFixExistingImport11.ts index 8822356c13a..786e0e39775 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport11.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport11.ts @@ -18,4 +18,4 @@ verify.importFixAtPosition([ v3, f1 }` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport12.ts b/tests/cases/fourslash/importNameCodeFixExistingImport12.ts index e00dee504c5..87ba29ab0aa 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport12.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport12.ts @@ -9,4 +9,4 @@ //// export var v2 = 5; //// export var v3 = 5; -verify.importFixAtPosition([`{ f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport2.ts b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts index 6a92976f4ef..1146f24aeae 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport2.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts @@ -12,5 +12,5 @@ verify.importFixAtPosition([ import { f1 } from "./module"; f1();`, `import * as ns from "./module"; -ns.f1();` -]); \ No newline at end of file +ns.f1();`, +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport3.ts b/tests/cases/fourslash/importNameCodeFixExistingImport3.ts index bc00e8d420a..9fc44378713 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport3.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport3.ts @@ -14,5 +14,5 @@ verify.importFixAtPosition([ ns.f1();`, `import d, * as ns from "./module" ; import { f1 } from "./module"; -f1();`, -]); \ No newline at end of file +f1();` +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport4.ts b/tests/cases/fourslash/importNameCodeFixExistingImport4.ts index d93cb73664e..1aaf34f598c 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport4.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport4.ts @@ -11,4 +11,4 @@ verify.importFixAtPosition([ `import d, { f1 } from "./module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport5.ts b/tests/cases/fourslash/importNameCodeFixExistingImport5.ts index ed9297124d9..bfcf888b17b 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport5.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport5.ts @@ -9,4 +9,4 @@ verify.importFixAtPosition([`import "./module"; import { f1 } from "./module"; -f1();`]); \ No newline at end of file +f1();`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport6.ts b/tests/cases/fourslash/importNameCodeFixExistingImport6.ts index 7ae157a51ce..0d3636e4439 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport6.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport6.ts @@ -10,4 +10,4 @@ //// export var v1 = 5; //// export function f1(); -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport7.ts b/tests/cases/fourslash/importNameCodeFixExistingImport7.ts index 249929eabc7..f0b1a77f690 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport7.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport7.ts @@ -7,4 +7,4 @@ //// export var v1 = 5; //// export function f1(); -verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file +verify.importFixAtPosition([`{ v1, f1 }`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport8.ts b/tests/cases/fourslash/importNameCodeFixExistingImport8.ts index da7beaa0a47..a1b676a8b83 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport8.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport8.ts @@ -9,4 +9,4 @@ //// export var v2 = 5; //// export var v3 = 5; -verify.importFixAtPosition([`{v1, v2, v3, f1,}`]); \ No newline at end of file +verify.importFixAtPosition([`{v1, v2, v3, f1,}`]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport9.ts b/tests/cases/fourslash/importNameCodeFixExistingImport9.ts index 51496abff12..67960de32d4 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport9.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport9.ts @@ -13,4 +13,4 @@ verify.importFixAtPosition([ `{ v1, f1 }` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts b/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts index f431e6356d1..de86ed13cd5 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts @@ -15,4 +15,4 @@ var x = ns.v1 + 5;`, `import ns = require("ambient-module"); import { v1 } from "ambient-module"; var x = v1 + 5;`, -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts index 1d7b5bc3e7f..75ef89ee4a5 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts @@ -12,4 +12,4 @@ verify.importFixAtPosition([ `import { f1 } from "ambient-module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts index 60504c89711..835850306f6 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts @@ -25,4 +25,4 @@ verify.importFixAtPosition([ `import * as ns from "yet-another-ambient-module"; import { v1 } from "ambient-module"; var x = v1 + 5;` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts index 999da4bffbb..a23d7684d0a 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts @@ -18,4 +18,4 @@ verify.importFixAtPosition([ import { f1 } from "ambient-module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts index 648293cce2e..dbd6c4ef26a 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts @@ -27,4 +27,4 @@ verify.importFixAtPosition([ `import * as ns from "yet-another-ambient-module" import { v1 } from "ambient-module"; var x = v1 + 5;` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts index e15c2cf4399..a48b381df68 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts @@ -16,4 +16,4 @@ verify.importFixAtPosition([ `import { f1 } from "b"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts b/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts index 3efe023e922..b27cbde3283 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts @@ -9,4 +9,4 @@ verify.importFixAtPosition([ `import f1 from "./module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts index 2372110437a..12566de406d 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts @@ -10,4 +10,4 @@ verify.importFixAtPosition([ `import { f1 } from "./module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts index 9f6cac0b7c1..b98345db9f6 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts @@ -15,4 +15,4 @@ verify.importFixAtPosition([ import { f1 } from "./Module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts index ca9330e9846..5d5c1fb61bc 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts @@ -10,4 +10,4 @@ verify.importFixAtPosition([ `import { f1 } from "../../other_dir/module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts index 6bffe41b27a..77b1545e3c0 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts @@ -13,4 +13,4 @@ verify.importFixAtPosition([ `import { f1 } from "fake-module/nested"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts index ff48fbe182c..80cb53d7e09 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts @@ -22,4 +22,4 @@ verify.importFixAtPosition([ `import { f1 } from "fake-module"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts index b1143cb4b41..f0e09885a6b 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts @@ -11,4 +11,4 @@ verify.importFixAtPosition([ `import { f1 } from "random"; f1();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts index 93cd6f92ef5..bd3fd9a84b3 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts @@ -19,4 +19,4 @@ verify.importFixAtPosition([ `import { foo } from "a"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts index bb0f1e6705a..5ac195e9ab4 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts @@ -19,4 +19,4 @@ verify.importFixAtPosition([ `import { foo } from "b/f2"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts index b455538de08..33b8d9330be 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths2.ts @@ -25,4 +25,4 @@ verify.importFixAtPosition([ `import { foo } from "b"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts b/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts index ae8ef03ccac..8721d7e0105 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts @@ -20,4 +20,4 @@ verify.importFixAtPosition([ `import { foo } from "./f2"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts index a6eb6a90759..cb7ef465aff 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts @@ -19,4 +19,4 @@ verify.importFixAtPosition([ `import { foo } from "random"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts index 2778f51bacf..1398a5d7866 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts @@ -20,4 +20,4 @@ verify.importFixAtPosition([ `import { foo } from "random"; foo();` -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts index 30b482a94d7..34cebad9415 100644 --- a/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts @@ -17,4 +17,4 @@ foo();`, `import * as ns from "./foo"; ns.foo();`, -]); \ No newline at end of file +]); diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts index 343b0692260..7a3d19e1532 100644 --- a/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts @@ -17,4 +17,4 @@ foo();`, `import { foo } from "bar"; foo();`, -]); \ No newline at end of file +]); From ca7d7f5946f089c6c94d75bc478f5dfdb10a540a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 1 May 2017 12:58:42 -0700 Subject: [PATCH 036/282] Only 100 spelling corrections for unknown symbols If your compilation has more than 100 unknown symbols, the problem is missing declarations, not typos. --- src/compiler/checker.ts | 5 +- .../maximum100SpellingSuggestions.errors.txt | 378 ++++++++++++++++++ .../maximum100SpellingSuggestions.js | 140 +++++++ .../compiler/maximum100SpellingSuggestions.ts | 14 + 4 files changed, 536 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/maximum100SpellingSuggestions.errors.txt create mode 100644 tests/baselines/reference/maximum100SpellingSuggestions.js create mode 100644 tests/cases/compiler/maximum100SpellingSuggestions.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7b7aaf9937c..76ff43f20e2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -318,6 +318,8 @@ namespace ts { const resolutionResults: boolean[] = []; const resolutionPropertyNames: TypeSystemPropertyName[] = []; + let suggestionCount = 0; + const maximumSuggestionCount = 100; const mergedSymbols: Symbol[] = []; const symbolLinks: SymbolLinks[] = []; const nodeLinks: NodeLinks[] = []; @@ -1091,9 +1093,10 @@ namespace ts { !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { let suggestion: string | undefined; - if (suggestedNameNotFoundMessage) { + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { + suggestionCount++; error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg), suggestion); } } diff --git a/tests/baselines/reference/maximum100SpellingSuggestions.errors.txt b/tests/baselines/reference/maximum100SpellingSuggestions.errors.txt new file mode 100644 index 00000000000..4f921104d77 --- /dev/null +++ b/tests/baselines/reference/maximum100SpellingSuggestions.errors.txt @@ -0,0 +1,378 @@ +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(3,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(4,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(5,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(6,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(7,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(8,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(9,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(10,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(11,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(12,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,1): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,6): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,11): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,16): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,21): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,26): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,31): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,36): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,41): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(13,46): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,1): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,6): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,11): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,16): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,21): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,26): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,31): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,36): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,41): error TS2304: Cannot find name 'any'. +tests/cases/compiler/maximum100SpellingSuggestions.ts(14,46): error TS2304: Cannot find name 'any'. + + +==== tests/cases/compiler/maximum100SpellingSuggestions.ts (120 errors) ==== + // 10 anys per line, 12 lines + // the last two lines should not have spelling suggestions + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + ~~~ +!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + any; any; any; any; any; any; any; any; any; any; + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + ~~~ +!!! error TS2304: Cannot find name 'any'. + \ No newline at end of file diff --git a/tests/baselines/reference/maximum100SpellingSuggestions.js b/tests/baselines/reference/maximum100SpellingSuggestions.js new file mode 100644 index 00000000000..5746091feb1 --- /dev/null +++ b/tests/baselines/reference/maximum100SpellingSuggestions.js @@ -0,0 +1,140 @@ +//// [maximum100SpellingSuggestions.ts] +// 10 anys per line, 12 lines +// the last two lines should not have spelling suggestions +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; + + +//// [maximum100SpellingSuggestions.js] +// 10 anys per line, 12 lines +// the last two lines should not have spelling suggestions +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; +any; diff --git a/tests/cases/compiler/maximum100SpellingSuggestions.ts b/tests/cases/compiler/maximum100SpellingSuggestions.ts new file mode 100644 index 00000000000..febc10c1c6f --- /dev/null +++ b/tests/cases/compiler/maximum100SpellingSuggestions.ts @@ -0,0 +1,14 @@ +// 10 anys per line, 12 lines +// the last two lines should not have spelling suggestions +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; +any; any; any; any; any; any; any; any; any; any; From eb33ba7d97f09b1c0835a7edc8983d0c12072ffa Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 1 May 2017 13:03:49 -0700 Subject: [PATCH 037/282] Fix semicolon lint --- src/compiler/utilities.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 1ce2cf2c991..02acacf9e7c 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4643,7 +4643,7 @@ namespace ts { current[j] = Math.min( previous[j] + 1, current[j - 1] + 1, - previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)) + previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); } // shift current back to previous, and then reuse previous' array const tmp = previous; From d37426d865f51aa8be2eca4f0d5c4260f6b8ed3a Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 1 May 2017 13:23:34 -0700 Subject: [PATCH 038/282] Fill out remaining factory functions --- src/compiler/checker.ts | 6 +- src/compiler/factory.ts | 801 ++++++++++-------- src/compiler/types.ts | 2 +- src/compiler/utilities.ts | 13 +- src/compiler/visitor.ts | 267 +++--- src/harness/unittests/transform.ts | 3 + src/services/codefixes/fixAddMissingMember.ts | 16 +- src/services/codefixes/helpers.ts | 2 +- 8 files changed, 603 insertions(+), 507 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 18e57303c12..0ec9f23266e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2389,7 +2389,7 @@ namespace ts { const formattedUnionTypes = formatUnionTypes((type).types); const unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); if (unionTypeNodes && unionTypeNodes.length > 0) { - return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, unionTypeNodes); + return createUnionTypeNode(unionTypeNodes); } else { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyUnionOrIntersection)) { @@ -2400,7 +2400,7 @@ namespace ts { } if (type.flags & TypeFlags.Intersection) { - return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, mapToTypeNodeArray((type as UnionType).types)); + return createIntersectionTypeNode(mapToTypeNodeArray((type as IntersectionType).types)); } if (objectFlags & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) { @@ -2660,7 +2660,7 @@ namespace ts { indexerTypeNode, /*initializer*/ undefined); const typeNode = typeToTypeNodeHelper(indexInfo.type); - return createIndexSignatureDeclaration( + return createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined, [indexingParameter], diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 95878917b3d..b8be8b7bcaa 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -214,248 +214,14 @@ namespace ts { : node; } - // Type Elements - - export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - const signatureDeclaration = createSynthesizedNode(kind) as SignatureDeclaration; - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - - function updateSignatureDeclaration(node: SignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - - export function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode; - } - - export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode; - } - - export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration; - } - - export function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { - return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration; - } - - export function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - - export function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) { - const methodSignature = createSignatureDeclaration(SyntaxKind.MethodSignature, typeParameters, parameters, type) as MethodSignature; - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - - export function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - - // Types - - export function createKeywordTypeNode(kind: KeywordTypeNode["kind"]) { - return createSynthesizedNode(kind); - } - - export function createThisTypeNode() { - return createSynthesizedNode(SyntaxKind.ThisType); - } - - export function createLiteralTypeNode(literal: Expression) { - const literalTypeNode = createSynthesizedNode(SyntaxKind.LiteralType) as LiteralTypeNode; - literalTypeNode.literal = literal; - return literalTypeNode; - } - - export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - - export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) { - const typeReference = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode; - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - - export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - - export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) { - const typePredicateNode = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode; - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - - export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - - export function createTypeQueryNode(exprName: EntityName) { - const typeQueryNode = createSynthesizedNode(SyntaxKind.TypeQuery) as TypeQueryNode; - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - - export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - - export function createArrayTypeNode(elementType: TypeNode) { - const arrayTypeNode = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode; - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - - export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) { - const unionTypeNode = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode; - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - - export function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - - export function createParenthesizedType(type: TypeNode) { - const node = createSynthesizedNode(SyntaxKind.ParenthesizedType); - node.type = type; - return node; - } - - export function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - - export function createTypeLiteralNode(members: TypeElement[]) { - const typeLiteralNode = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode; - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - - export function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - - export function createTupleTypeNode(elementTypes: TypeNode[]) { - const tupleTypeNode = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode; - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - - export function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - - export function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { - const mappedTypeNode = createSynthesizedNode(SyntaxKind.MappedType) as MappedTypeNode; - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - - export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - - export function createTypeOperatorNode(type: TypeNode) { - const typeOperatorNode = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode; - typeOperatorNode.operator = SyntaxKind.KeyOfKeyword; - typeOperatorNode.type = type; - return typeOperatorNode; - } - - export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - - export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) { - const indexedAccessTypeNode = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode; - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - - export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - - // Type Declarations + // Signature elements export function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) { - const typeParameter = createSynthesizedNode(SyntaxKind.TypeParameter) as TypeParameterDeclaration; - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - - return typeParameter; + const node = createSynthesizedNode(SyntaxKind.TypeParameter) as TypeParameterDeclaration; + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } export function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) { @@ -466,46 +232,6 @@ namespace ts { : node; } - // Signature elements - - export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature { - const propertySignature = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature; - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - - export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - - export function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration { - const indexSignature = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration; - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - - export function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - - // Signature elements - export function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression) { const node = createSynthesizedNode(SyntaxKind.Parameter); node.decorators = asNodeArray(decorators); @@ -542,7 +268,26 @@ namespace ts { : node; } - // Type members + + // Type Elements + + export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature { + const node = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + + export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { + return node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) + : node; + } export function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression) { const node = createSynthesizedNode(SyntaxKind.PropertyDeclaration); @@ -565,7 +310,24 @@ namespace ts { : node; } - export function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { + export function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) { + const node = createSignatureDeclaration(SyntaxKind.MethodSignature, typeParameters, parameters, type) as MethodSignature; + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + + export function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + + export function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.MethodDeclaration); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -588,7 +350,7 @@ namespace ts { || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } @@ -656,6 +418,254 @@ namespace ts { : node; } + export function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration; + } + + export function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration; + } + + export function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration { + const node = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration; + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + + export function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + + /* @internal */ + export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + const node = createSynthesizedNode(kind) as SignatureDeclaration; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + + function updateSignatureDeclaration(node: T, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): T { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + + // Types + + export function createKeywordTypeNode(kind: KeywordTypeNode["kind"]) { + return createSynthesizedNode(kind); + } + + export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode; + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + + export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + + export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) { + const node = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode; + node.typeName = asName(typeName); + node.typeArguments = asNodeArray(typeArguments); + return node; + } + + export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + + export function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode; + } + + export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { + return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode; + } + + export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + + export function createTypeQueryNode(exprName: EntityName) { + const node = createSynthesizedNode(SyntaxKind.TypeQuery) as TypeQueryNode; + node.exprName = exprName; + return node; + } + + export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + + export function createTypeLiteralNode(members: TypeElement[]) { + const node = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode; + node.members = createNodeArray(members); + return node; + } + + export function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + + export function createArrayTypeNode(elementType: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode; + node.elementType = elementType; + return node; + } + + export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + + export function createTupleTypeNode(elementTypes: TypeNode[]) { + const node = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode; + node.elementTypes = createNodeArray(elementTypes); + return node; + } + + export function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + + export function createUnionTypeNode(types: TypeNode[]): UnionTypeNode { + return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types); + } + + export function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray) { + return updateUnionOrIntersectionTypeNode(node, types); + } + + export function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode { + return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types); + } + + export function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray) { + return updateUnionOrIntersectionTypeNode(node, types); + } + + export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) { + const node = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode; + node.types = createNodeArray(types); + return node; + } + + function updateUnionOrIntersectionTypeNode(node: T, types: NodeArray): T { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + + export function createParenthesizedType(type: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.ParenthesizedType); + node.type = type; + return node; + } + + export function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + + export function createThisTypeNode() { + return createSynthesizedNode(SyntaxKind.ThisType); + } + + export function createTypeOperatorNode(type: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode; + node.operator = SyntaxKind.KeyOfKeyword; + node.type = type; + return node; + } + + export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + + export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode; + node.objectType = objectType; + node.indexType = indexType; + return node; + } + + export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + + export function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { + const node = createSynthesizedNode(SyntaxKind.MappedType) as MappedTypeNode; + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + + export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + + export function createLiteralTypeNode(literal: Expression) { + const node = createSynthesizedNode(SyntaxKind.LiteralType) as LiteralTypeNode; + node.literal = literal; + return node; + } + + export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + // Binding Patterns export function createObjectBindingPattern(elements: BindingElement[]) { @@ -705,10 +715,7 @@ namespace ts { export function createArrayLiteral(elements?: Expression[], multiLine?: boolean) { const node = createSynthesizedNode(SyntaxKind.ArrayLiteralExpression); node.elements = parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { - node.multiLine = true; - } - + if (multiLine) node.multiLine = true; return node; } @@ -721,9 +728,7 @@ namespace ts { export function createObjectLiteral(properties?: ObjectLiteralElementLike[], multiLine?: boolean) { const node = createSynthesizedNode(SyntaxKind.ObjectLiteralExpression); node.properties = createNodeArray(properties); - if (multiLine) { - node.multiLine = true; - } + if (multiLine) node.multiLine = true; return node; } @@ -773,9 +778,9 @@ namespace ts { } export function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -1099,6 +1104,19 @@ namespace ts { : node; } + export function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier) { + const node = createSynthesizedNode(SyntaxKind.MetaProperty); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + + export function updateMetaProperty(node: MetaProperty, name: Identifier) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + // Misc export function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail) { @@ -1115,6 +1133,10 @@ namespace ts { : node; } + export function createSemicolonClassElement() { + return createSynthesizedNode(SyntaxKind.SemicolonClassElement); + } + // Element export function createBlock(statements: Statement[], multiLine?: boolean): Block { @@ -1125,7 +1147,7 @@ namespace ts { } export function updateBlock(node: Block, statements: Statement[]) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -1145,35 +1167,6 @@ namespace ts { : node; } - export function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags) { - const node = createSynthesizedNode(SyntaxKind.VariableDeclarationList); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - - export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - - export function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression) { - const node = createSynthesizedNode(SyntaxKind.VariableDeclaration); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; - return node; - } - - export function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - export function createEmptyStatement() { return createSynthesizedNode(SyntaxKind.EmptyStatement); } @@ -1392,6 +1385,39 @@ namespace ts { : node; } + export function createDebuggerStatement() { + return createSynthesizedNode(SyntaxKind.DebuggerStatement); + } + + export function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression) { + const node = createSynthesizedNode(SyntaxKind.VariableDeclaration); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + + export function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + + export function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags) { + const node = createSynthesizedNode(SyntaxKind.VariableDeclarationList); + node.flags |= flags & NodeFlags.BlockScoped; + node.declarations = createNodeArray(declarations); + return node; + } + + export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + export function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.FunctionDeclaration); node.decorators = asNodeArray(decorators); @@ -1462,6 +1488,22 @@ namespace ts { : node; } + export function createTypeAliasDeclaration(name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { + const node = createSynthesizedNode(SyntaxKind.TypeAliasDeclaration); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + + export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { + return node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(name, typeParameters, type), node) + : node; + } + export function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]) { const node = createSynthesizedNode(SyntaxKind.EnumDeclaration); node.decorators = asNodeArray(decorators); @@ -1482,7 +1524,7 @@ namespace ts { export function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags) { const node = createSynthesizedNode(SyntaxKind.ModuleDeclaration); - node.flags |= flags; + node.flags |= flags & (NodeFlags.Namespace | NodeFlags.NestedNamespace | NodeFlags.GlobalAugmentation); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -1523,6 +1565,18 @@ namespace ts { : node; } + export function createNamespaceExportDeclaration(name: string | Identifier) { + const node = createSynthesizedNode(SyntaxKind.NamespaceExportDeclaration); + node.name = asName(name); + return node; + } + + export function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + export function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference) { const node = createSynthesizedNode(SyntaxKind.ImportEqualsDeclaration); node.decorators = asNodeArray(decorators); @@ -1553,7 +1607,8 @@ namespace ts { export function updateImportDeclaration(node: ImportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -1743,19 +1798,6 @@ namespace ts { : node; } - export function createJsxAttributes(properties: JsxAttributeLike[]) { - const jsxAttributes = createSynthesizedNode(SyntaxKind.JsxAttributes); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - - export function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - export function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression) { const node = createSynthesizedNode(SyntaxKind.JsxAttribute); node.name = name; @@ -1770,6 +1812,18 @@ namespace ts { : node; } + export function createJsxAttributes(properties: JsxAttributeLike[]) { + const node = createSynthesizedNode(SyntaxKind.JsxAttributes); + node.properties = createNodeArray(properties); + return node; + } + + export function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + export function createJsxSpreadAttribute(expression: Expression) { const node = createSynthesizedNode(SyntaxKind.JsxSpreadAttribute); node.expression = expression; @@ -1797,20 +1851,6 @@ namespace ts { // Clauses - export function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]) { - const node = createSynthesizedNode(SyntaxKind.HeritageClause); - node.token = token; - node.types = createNodeArray(types); - return node; - } - - export function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - export function createCaseClause(expression: Expression, statements: Statement[]) { const node = createSynthesizedNode(SyntaxKind.CaseClause); node.expression = parenthesizeExpressionForList(expression); @@ -1819,10 +1859,10 @@ namespace ts { } export function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } export function createDefaultClause(statements: Statement[]) { @@ -1832,12 +1872,24 @@ namespace ts { } export function updateDefaultClause(node: DefaultClause, statements: Statement[]) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; + } + + export function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]) { + const node = createSynthesizedNode(SyntaxKind.HeritageClause); + node.token = token; + node.types = createNodeArray(types); return node; } + export function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + export function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block) { const node = createSynthesizedNode(SyntaxKind.CatchClause); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -1846,10 +1898,10 @@ namespace ts { } export function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } // Property assignments @@ -1863,10 +1915,10 @@ namespace ts { } export function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } export function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression) { @@ -1877,10 +1929,10 @@ namespace ts { } export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } export function createSpreadAssignment(expression: Expression) { @@ -1890,10 +1942,9 @@ namespace ts { } export function updateSpreadAssignment(node: SpreadAssignment, expression: Expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } // Enum diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 57cf17f7100..327c71f8de4 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1506,7 +1506,7 @@ namespace ts { // for the same reasons we treat NewExpression as a PrimaryExpression. export interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 646a7b22e3f..22a0684fa56 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3649,7 +3649,18 @@ namespace ts { || kind === SyntaxKind.GetAccessor || kind === SyntaxKind.SetAccessor || kind === SyntaxKind.IndexSignature - || kind === SyntaxKind.SemicolonClassElement; + || kind === SyntaxKind.SemicolonClassElement + || kind === SyntaxKind.MissingDeclaration; + } + + export function isTypeElement(node: Node): node is TypeElement { + const kind = node.kind; + return kind === SyntaxKind.ConstructSignature + || kind === SyntaxKind.CallSignature + || kind === SyntaxKind.PropertySignature + || kind === SyntaxKind.MethodSignature + || kind === SyntaxKind.IndexSignature + || kind === SyntaxKind.MissingDeclaration; } export function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike { diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 54cea3168e1..e434dadeaf7 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -218,16 +218,7 @@ namespace ts { return node; } - switch (node.kind) { - case SyntaxKind.SemicolonClassElement: - case SyntaxKind.EmptyStatement: - case SyntaxKind.OmittedExpression: - case SyntaxKind.DebuggerStatement: - case SyntaxKind.EndOfDeclarationMarker: - case SyntaxKind.MissingDeclaration: - // No need to visit nodes with no children. - return node; - + switch (kind) { // Names case SyntaxKind.QualifiedName: return updateQualifiedName(node, @@ -238,45 +229,13 @@ namespace ts { return updateComputedPropertyName(node, visitNode((node).expression, visitor, isExpression)); - // Signatures and Signature Elements - case SyntaxKind.FunctionType: - return updateFunctionTypeNode(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); + // Signature elements - case SyntaxKind.ConstructorType: - return updateConstructorTypeNode(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.CallSignature: - return updateCallSignatureDeclaration(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.ConstructSignature: - return updateConstructSignatureDeclaration(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.MethodSignature: - return updateMethodSignature(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameter), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode), - visitNode((node).name, visitor, isPropertyName), - visitNode((node).questionToken, tokenVisitor, isToken)); - - case SyntaxKind.IndexSignature: - return updateIndexSignatureDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type, visitor, isTypeNode)); + case SyntaxKind.TypeParameter: + return updateTypeParameterDeclaration(node, + visitNode((node).name, visitor, isIdentifier), + visitNode((node).constraint, visitor, isTypeNode), + visitNode((node).default, visitor, isTypeNode)); case SyntaxKind.Parameter: return updateParameter(node, @@ -292,67 +251,7 @@ namespace ts { return updateDecorator(node, visitNode((node).expression, visitor, isExpression)); - // Types - - case SyntaxKind.TypeReference: - return updateTypeReferenceNode(node, - visitNode((node).typeName, visitor, isEntityName), - nodesVisitor((node).typeArguments, visitor, isTypeNode)); - - case SyntaxKind.TypePredicate: - return updateTypePredicateNode(node, - visitNode((node).parameterName, visitor), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.TypeQuery: - return updateTypeQueryNode((node), visitNode((node).exprName, visitor, isEntityName)); - - case SyntaxKind.TypeLiteral: - return updateTypeLiteralNode((node), nodesVisitor((node).members, visitor)); - - case SyntaxKind.ArrayType: - return updateArrayTypeNode(node, visitNode((node).elementType, visitor, isTypeNode)); - - case SyntaxKind.TupleType: - return updateTypleTypeNode((node), nodesVisitor((node).elementTypes, visitor, isTypeNode)); - - case SyntaxKind.UnionType: - case SyntaxKind.IntersectionType: - return updateUnionOrIntersectionTypeNode(node, - nodesVisitor((node).types, visitor, isTypeNode)); - - case SyntaxKind.ParenthesizedType: - return updateParenthesizedType(node, - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.TypeOperator: - return updateTypeOperatorNode(node, visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.IndexedAccessType: - return updateIndexedAccessTypeNode((node), - visitNode((node).objectType, visitor, isTypeNode), - visitNode((node).indexType, visitor, isTypeNode)); - - case SyntaxKind.MappedType: - return updateMappedTypeNode((node), - visitNode((node).readonlyToken, tokenVisitor, isToken), - visitNode((node).typeParameter, visitor, isTypeParameter), - visitNode((node).questionToken, tokenVisitor, isToken), - visitNode((node).type, visitor, isTypeNode)); - - case SyntaxKind.LiteralType: - return updateLiteralTypeNode(node, - visitNode((node).literal, visitor, isExpression)); - - // Type Declarations - - case SyntaxKind.TypeParameter: - return updateTypeParameterDeclaration(node, - visitNode((node).name, visitor, isIdentifier), - visitNode((node).constraint, visitor, isTypeNode), - visitNode((node).default, visitor, isTypeNode)); - - // Type members + // Type elements case SyntaxKind.PropertySignature: return updatePropertySignature((node), @@ -369,6 +268,14 @@ namespace ts { visitNode((node).type, visitor, isTypeNode), visitNode((node).initializer, visitor, isExpression)); + case SyntaxKind.MethodSignature: + return updateMethodSignature(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode), + visitNode((node).name, visitor, isPropertyName), + visitNode((node).questionToken, tokenVisitor, isToken)); + case SyntaxKind.MethodDeclaration: return updateMethod(node, nodesVisitor((node).decorators, visitor, isDecorator), @@ -405,7 +312,99 @@ namespace ts { visitParameterList((node).parameters, visitor, context, nodesVisitor), visitFunctionBody((node).body, visitor, context)); + case SyntaxKind.CallSignature: + return updateCallSignature(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.ConstructSignature: + return updateConstructSignature(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.IndexSignature: + return updateIndexSignature(node, + nodesVisitor((node).decorators, visitor, isDecorator), + nodesVisitor((node).modifiers, visitor, isModifier), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + // Types + + case SyntaxKind.TypePredicate: + return updateTypePredicateNode(node, + visitNode((node).parameterName, visitor), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.TypeReference: + return updateTypeReferenceNode(node, + visitNode((node).typeName, visitor, isEntityName), + nodesVisitor((node).typeArguments, visitor, isTypeNode)); + + case SyntaxKind.FunctionType: + return updateFunctionTypeNode(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.ConstructorType: + return updateConstructorTypeNode(node, + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).parameters, visitor, isParameterDeclaration), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.TypeQuery: + return updateTypeQueryNode((node), + visitNode((node).exprName, visitor, isEntityName)); + + case SyntaxKind.TypeLiteral: + return updateTypeLiteralNode((node), + nodesVisitor((node).members, visitor, isTypeElement)); + + case SyntaxKind.ArrayType: + return updateArrayTypeNode(node, + visitNode((node).elementType, visitor, isTypeNode)); + + case SyntaxKind.TupleType: + return updateTypleTypeNode((node), + nodesVisitor((node).elementTypes, visitor, isTypeNode)); + + case SyntaxKind.UnionType: + return updateUnionTypeNode(node, + nodesVisitor((node).types, visitor, isTypeNode)); + + case SyntaxKind.IntersectionType: + return updateIntersectionTypeNode(node, + nodesVisitor((node).types, visitor, isTypeNode)); + + case SyntaxKind.ParenthesizedType: + return updateParenthesizedType(node, + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.TypeOperator: + return updateTypeOperatorNode(node, + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.IndexedAccessType: + return updateIndexedAccessTypeNode((node), + visitNode((node).objectType, visitor, isTypeNode), + visitNode((node).indexType, visitor, isTypeNode)); + + case SyntaxKind.MappedType: + return updateMappedTypeNode((node), + visitNode((node).readonlyToken, tokenVisitor, isToken), + visitNode((node).typeParameter, visitor, isTypeParameter), + visitNode((node).questionToken, tokenVisitor, isToken), + visitNode((node).type, visitor, isTypeNode)); + + case SyntaxKind.LiteralType: + return updateLiteralTypeNode(node, + visitNode((node).literal, visitor, isExpression)); + // Binding patterns + case SyntaxKind.ObjectBindingPattern: return updateObjectBindingPattern(node, nodesVisitor((node).elements, visitor, isBindingElement)); @@ -422,6 +421,7 @@ namespace ts { visitNode((node).initializer, visitor, isExpression)); // Expression + case SyntaxKind.ArrayLiteralExpression: return updateArrayLiteral(node, nodesVisitor((node).elements, visitor, isExpression)); @@ -500,11 +500,6 @@ namespace ts { return updateAwait(node, visitNode((node).expression, visitor, isExpression)); - case SyntaxKind.BinaryExpression: - return updateBinary(node, - visitNode((node).left, visitor, isExpression), - visitNode((node).right, visitor, isExpression)); - case SyntaxKind.PrefixUnaryExpression: return updatePrefix(node, visitNode((node).operand, visitor, isExpression)); @@ -513,6 +508,11 @@ namespace ts { return updatePostfix(node, visitNode((node).operand, visitor, isExpression)); + case SyntaxKind.BinaryExpression: + return updateBinary(node, + visitNode((node).left, visitor, isExpression), + visitNode((node).right, visitor, isExpression)); + case SyntaxKind.ConditionalExpression: return updateConditional(node, visitNode((node).condition, visitor, isExpression), @@ -555,13 +555,19 @@ namespace ts { return updateNonNullExpression(node, visitNode((node).expression, visitor, isExpression)); + case SyntaxKind.MetaProperty: + return updateMetaProperty(node, + visitNode((node).name, visitor, isIdentifier)); + // Misc + case SyntaxKind.TemplateSpan: return updateTemplateSpan(node, visitNode((node).expression, visitor, isExpression), visitNode((node).literal, visitor, isTemplateMiddleOrTemplateTail)); // Element + case SyntaxKind.Block: return updateBlock(node, nodesVisitor((node).statements, visitor, isStatement)); @@ -678,6 +684,21 @@ namespace ts { nodesVisitor((node).heritageClauses, visitor, isHeritageClause), nodesVisitor((node).members, visitor, isClassElement)); + case SyntaxKind.InterfaceDeclaration: + return updateInterfaceDeclaration(node, + nodesVisitor((node).decorators, visitor, isDecorator), + nodesVisitor((node).modifiers, visitor, isModifier), + visitNode((node).name, visitor, isIdentifier), + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + nodesVisitor((node).heritageClauses, visitor, isHeritageClause), + nodesVisitor((node).members, visitor, isTypeElement)); + + case SyntaxKind.TypeAliasDeclaration: + return updateTypeAliasDeclaration(node, + visitNode((node).name, visitor, isIdentifier), + nodesVisitor((node).typeParameters, visitor, isTypeParameter), + visitNode((node).type, visitor, isTypeNode)); + case SyntaxKind.EnumDeclaration: return updateEnumDeclaration(node, nodesVisitor((node).decorators, visitor, isDecorator), @@ -700,6 +721,10 @@ namespace ts { return updateCaseBlock(node, nodesVisitor((node).clauses, visitor, isCaseOrDefaultClause)); + case SyntaxKind.NamespaceExportDeclaration: + return updateNamespaceExportDeclaration(node, + visitNode((node).name, visitor, isIdentifier)); + case SyntaxKind.ImportEqualsDeclaration: return updateImportEqualsDeclaration(node, nodesVisitor((node).decorators, visitor, isDecorator), @@ -755,21 +780,19 @@ namespace ts { visitNode((node).name, visitor, isIdentifier)); // Module references + case SyntaxKind.ExternalModuleReference: return updateExternalModuleReference(node, visitNode((node).expression, visitor, isExpression)); // JSX + case SyntaxKind.JsxElement: return updateJsxElement(node, visitNode((node).openingElement, visitor, isJsxOpeningElement), nodesVisitor((node).children, visitor, isJsxChild), visitNode((node).closingElement, visitor, isJsxClosingElement)); - case SyntaxKind.JsxAttributes: - return updateJsxAttributes(node, - nodesVisitor((node).properties, visitor, isJsxAttributeLike)); - case SyntaxKind.JsxSelfClosingElement: return updateJsxSelfClosingElement(node, visitNode((node).tagName, visitor, isJsxTagNameExpression), @@ -789,6 +812,10 @@ namespace ts { visitNode((node).name, visitor, isIdentifier), visitNode((node).initializer, visitor, isStringLiteralOrJsxExpression)); + case SyntaxKind.JsxAttributes: + return updateJsxAttributes(node, + nodesVisitor((node).properties, visitor, isJsxAttributeLike)); + case SyntaxKind.JsxSpreadAttribute: return updateJsxSpreadAttribute(node, visitNode((node).expression, visitor, isExpression)); @@ -798,6 +825,7 @@ namespace ts { visitNode((node).expression, visitor, isExpression)); // Clauses + case SyntaxKind.CaseClause: return updateCaseClause(node, visitNode((node).expression, visitor, isExpression), @@ -817,6 +845,7 @@ namespace ts { visitNode((node).block, visitor, isBlock)); // Property assignments + case SyntaxKind.PropertyAssignment: return updatePropertyAssignment(node, visitNode((node).name, visitor, isPropertyName), @@ -848,8 +877,10 @@ namespace ts { visitNode((node).expression, visitor, isExpression)); default: + // No need to visit nodes with no children. return node; } + } /** diff --git a/src/harness/unittests/transform.ts b/src/harness/unittests/transform.ts index 71f50ed94a9..b124c380e05 100644 --- a/src/harness/unittests/transform.ts +++ b/src/harness/unittests/transform.ts @@ -68,6 +68,9 @@ namespace ts { transformers: { before: [replaceUndefinedWithVoid0], after: [replaceIdentifiersNamedOldNameWithNewName] + }, + compilerOptions: { + newLine: NewLineKind.LineFeed } }).outputText; }); diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 8e1d0ac2f29..5bb24d397d9 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -110,16 +110,16 @@ namespace ts.codefix { if (!isStatic) { const stringTypeNode = createKeywordTypeNode(SyntaxKind.StringKeyword); const indexingParameter = createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", - /*questionToken*/ undefined, + /*questionToken*/ undefined, stringTypeNode, - /*initializer*/ undefined); - const indexSignature = createIndexSignatureDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, + /*initializer*/ undefined); + const indexSignature = createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 0de04d7a9b9..9312e66cc48 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -200,7 +200,7 @@ namespace ts.codefix { } export function createStubbedMethod(modifiers: Modifier[], name: PropertyName, optional: boolean, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], returnType: TypeNode | undefined) { - return createMethodDeclaration( + return createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, From c343dd382786b86857d91a64677e986e7cb0ff70 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 1 May 2017 18:05:50 -0700 Subject: [PATCH 039/282] Fix over agressive async delegation --- src/compiler/transformers/esnext.ts | 25 +++++---- ...ter.asyncGenerators.classMethods.es2015.js | 16 +++--- ...mitter.asyncGenerators.classMethods.es5.js | 56 ++++++++++--------- ...cGenerators.functionDeclarations.es2015.js | 16 +++--- ...syncGenerators.functionDeclarations.es5.js | 56 ++++++++++--------- ...ncGenerators.functionExpressions.es2015.js | 16 +++--- ...asyncGenerators.functionExpressions.es5.js | 56 ++++++++++--------- ...cGenerators.objectLiteralMethods.es2015.js | 16 +++--- ...syncGenerators.objectLiteralMethods.es5.js | 56 ++++++++++--------- 9 files changed, 170 insertions(+), 143 deletions(-) diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 3aa5be551a6..29cdbad5e7f 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -126,16 +126,19 @@ namespace ts { function visitYieldExpression(node: YieldExpression) { if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { const expression = visitNode(node.expression, visitor, isExpression); - return updateYield( + const delegator = node.asteriskToken && updateYield( node, node.asteriskToken, - node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : createArrayLiteral( - expression - ? [createLiteral("yield"), expression] - : [createLiteral("yield")] - ) + createAsyncDelegatorHelper(context, expression, expression) + ); + return updateYield( + node, + /*asteriskToken*/ undefined, + createArrayLiteral( + delegator ? [createLiteral("await"), delegator] : + expression ? [createLiteral("yield"), expression] : + [createLiteral("yield")] + ) ); } return visitEachChild(node, visitor, context); @@ -922,9 +925,9 @@ namespace ts { scoped: false, text: ` var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; ` }; diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js index fbefef62d05..58a4306c113 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js @@ -124,9 +124,9 @@ class C3 { } //// [C4.js] var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -149,7 +149,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar class C4 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator([1]); + const x = yield ["await", yield* __asyncDelegator([1])]; }); } } @@ -168,9 +168,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -180,7 +180,7 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { class C5 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; }); } } diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js index 0c58c4735a0..cb4418936be 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js @@ -260,9 +260,9 @@ var __generator = (this && this.__generator) || function (thisArg, body) { } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -297,12 +297,15 @@ var C4 = (function () { } C4.prototype.f = function () { return __asyncGenerator(this, arguments, function f_1() { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator([1]))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); @@ -352,9 +355,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -376,19 +379,22 @@ var C5 = (function () { } C5.prototype.f = function () { return __asyncGenerator(this, arguments, function f_1() { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })()))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, ["yield", 1]]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })()))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js index daf188ba33f..a3a6baf319a 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js @@ -87,9 +87,9 @@ function f3() { } //// [F4.js] var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -111,7 +111,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar }; function f4() { return __asyncGenerator(this, arguments, function* f4_1() { - const x = yield* __asyncDelegator([1]); + const x = yield ["await", yield* __asyncDelegator([1])]; }); } //// [F5.js] @@ -129,9 +129,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -140,7 +140,7 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; function f5() { return __asyncGenerator(this, arguments, function* f5_1() { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; }); } //// [F6.js] diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js index 71f685e24dd..1e75fb61c2f 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js @@ -214,9 +214,9 @@ var __generator = (this && this.__generator) || function (thisArg, body) { } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -248,12 +248,15 @@ var __values = (this && this.__values) || function (o) { }; function f4() { return __asyncGenerator(this, arguments, function f4_1() { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator([1]))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); @@ -301,9 +304,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -322,19 +325,22 @@ var __values = (this && this.__values) || function (o) { }; function f5() { return __asyncGenerator(this, arguments, function f5_1() { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })()))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, ["yield", 1]]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })()))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js index bb2562db780..475445b2f0a 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js @@ -87,9 +87,9 @@ const f3 = function () { }; //// [F4.js] var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -111,7 +111,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar }; const f4 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield* __asyncDelegator([1]); + const x = yield ["await", yield* __asyncDelegator([1])]; }); }; //// [F5.js] @@ -129,9 +129,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -140,7 +140,7 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; const f5 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; }); }; //// [F6.js] diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js index 1863548c141..bb94d82d7b6 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js @@ -214,9 +214,9 @@ var __generator = (this && this.__generator) || function (thisArg, body) { } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -248,12 +248,15 @@ var __values = (this && this.__values) || function (o) { }; var f4 = function () { return __asyncGenerator(this, arguments, function () { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator([1]))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); @@ -301,9 +304,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -322,19 +325,22 @@ var __values = (this && this.__values) || function (o) { }; var f5 = function () { return __asyncGenerator(this, arguments, function () { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })()))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, ["yield", 1]]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })()))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js index 5a200349c02..eedbfaf5998 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js @@ -107,9 +107,9 @@ const o3 = { }; //// [O4.js] var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -132,7 +132,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar const o4 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator([1]); + const x = yield ["await", yield* __asyncDelegator([1])]; }); } }; @@ -151,9 +151,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -163,7 +163,7 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { const o5 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })()); + const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; }); } }; diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js index abb3f0ca074..c108d49a26f 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js @@ -234,9 +234,9 @@ var __generator = (this && this.__generator) || function (thisArg, body) { } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -269,12 +269,15 @@ var __values = (this && this.__values) || function (o) { var o4 = { f: function () { return __asyncGenerator(this, arguments, function f_1() { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator([1]))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); @@ -323,9 +326,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { c = void 0, f(v), next(); } }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, f; + return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -345,19 +348,22 @@ var __values = (this && this.__values) || function (o) { var o5 = { f: function () { return __asyncGenerator(this, arguments, function f_1() { - var x; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })()))]; - case 1: - x = _a.sent(); + var x, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["await"]; + return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, ["yield", 1]]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })()))]; + case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + case 2: + x = _b.sent(); return [2 /*return*/]; } }); From 78ece7bfb1c81207568a83c60cd76d7e61b71482 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Tue, 2 May 2017 12:02:12 +0900 Subject: [PATCH 040/282] direct isInAmbientContext --- src/compiler/binder.ts | 21 +------ .../collisionArgumentsFunction.errors.txt | 15 ++--- .../reference/collisionArgumentsFunction.js | 19 ++----- .../reference/collisionArgumentsInType.js | 2 - .../collisionArgumentsInType.symbols | 57 +++++++++---------- .../reference/collisionArgumentsInType.types | 3 - .../collisionArgumentsInterfaceMembers.js | 2 - ...collisionArgumentsInterfaceMembers.symbols | 51 ++++++++--------- .../collisionArgumentsInterfaceMembers.types | 3 - .../compiler/collisionArgumentsFunction.ts | 15 ++--- .../compiler/collisionArgumentsInType.ts | 1 - .../collisionArgumentsInterfaceMembers.ts | 1 - 12 files changed, 72 insertions(+), 118 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 759e56d449c..562a650a7f0 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2503,27 +2503,8 @@ namespace ts { } } - function needParameterStrictModeCheck(node: Node) { - if (node.parent.kind === SyntaxKind.ConstructorType || node.parent.kind === SyntaxKind.FunctionType) { - return false; - } - - if (node.parent.parent && ( - node.parent.parent.kind === SyntaxKind.InterfaceDeclaration || - node.parent.parent.kind === SyntaxKind.TypeLiteral - )) { - return false; - } - - if (isDeclarationFile(file) || isInAmbientContext(node)) { - return false; - } - - return true; - } - function bindParameter(node: ParameterDeclaration) { - if (inStrictMode && needParameterStrictModeCheck(node)) { + if (inStrictMode && !isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); diff --git a/tests/baselines/reference/collisionArgumentsFunction.errors.txt b/tests/baselines/reference/collisionArgumentsFunction.errors.txt index f5388af6a14..a557e9cbcba 100644 --- a/tests/baselines/reference/collisionArgumentsFunction.errors.txt +++ b/tests/baselines/reference/collisionArgumentsFunction.errors.txt @@ -51,12 +51,9 @@ tests/cases/compiler/collisionArgumentsFunction.ts(30,22): error TS2396: Duplica var arguments: any; // No error } - namespace strict { - "use strict"; - declare function f5(arguments: number, ...rest); // no codegen no error - declare function f5(arguments: string, ...rest); // no codegen no error - declare function f52(i: number, ...arguments); // no codegen no error - declare function f52(i: string, ...arguments); // no codegen no error - declare function f6(arguments: number); // no codegen no error - declare function f6(arguments: string); // no codegen no error - } \ No newline at end of file + declare function f5(arguments: number, ...rest); // no codegen no error + declare function f5(arguments: string, ...rest); // no codegen no error + declare function f52(i: number, ...arguments); // no codegen no error + declare function f52(i: string, ...arguments); // no codegen no error + declare function f6(arguments: number); // no codegen no error + declare function f6(arguments: string); // no codegen no error \ No newline at end of file diff --git a/tests/baselines/reference/collisionArgumentsFunction.js b/tests/baselines/reference/collisionArgumentsFunction.js index 64cd2682a4a..c6a26baa495 100644 --- a/tests/baselines/reference/collisionArgumentsFunction.js +++ b/tests/baselines/reference/collisionArgumentsFunction.js @@ -37,15 +37,12 @@ function f4NoError(arguments: any) { // no error var arguments: any; // No error } -namespace strict { - "use strict"; - declare function f5(arguments: number, ...rest); // no codegen no error - declare function f5(arguments: string, ...rest); // no codegen no error - declare function f52(i: number, ...arguments); // no codegen no error - declare function f52(i: string, ...arguments); // no codegen no error - declare function f6(arguments: number); // no codegen no error - declare function f6(arguments: string); // no codegen no error -} +declare function f5(arguments: number, ...rest); // no codegen no error +declare function f5(arguments: string, ...rest); // no codegen no error +declare function f52(i: number, ...arguments); // no codegen no error +declare function f52(i: string, ...arguments); // no codegen no error +declare function f6(arguments: number); // no codegen no error +declare function f6(arguments: string); // no codegen no error //// [collisionArgumentsFunction.js] // Functions @@ -93,7 +90,3 @@ function f42(i) { function f4NoError(arguments) { var arguments; // No error } -var strict; -(function (strict) { - "use strict"; -})(strict || (strict = {})); diff --git a/tests/baselines/reference/collisionArgumentsInType.js b/tests/baselines/reference/collisionArgumentsInType.js index e9ff629f76e..4db7c930775 100644 --- a/tests/baselines/reference/collisionArgumentsInType.js +++ b/tests/baselines/reference/collisionArgumentsInType.js @@ -1,5 +1,4 @@ //// [collisionArgumentsInType.ts] -"use strict"; var v1: (i: number, ...arguments) => void; // no error - no code gen var v12: (arguments: number, ...restParameters) => void; // no error - no code gen var v2: { @@ -16,7 +15,6 @@ var v21: { } //// [collisionArgumentsInType.js] -"use strict"; var v1; // no error - no code gen var v12; // no error - no code gen var v2; diff --git a/tests/baselines/reference/collisionArgumentsInType.symbols b/tests/baselines/reference/collisionArgumentsInType.symbols index d2ec9ce6705..94c9374c7cd 100644 --- a/tests/baselines/reference/collisionArgumentsInType.symbols +++ b/tests/baselines/reference/collisionArgumentsInType.symbols @@ -1,54 +1,53 @@ === tests/cases/compiler/collisionArgumentsInType.ts === -"use strict"; var v1: (i: number, ...arguments) => void; // no error - no code gen ->v1 : Symbol(v1, Decl(collisionArgumentsInType.ts, 1, 3)) ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 1, 9)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 1, 19)) +>v1 : Symbol(v1, Decl(collisionArgumentsInType.ts, 0, 3)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 0, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 0, 19)) var v12: (arguments: number, ...restParameters) => void; // no error - no code gen ->v12 : Symbol(v12, Decl(collisionArgumentsInType.ts, 2, 3)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 2, 10)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 2, 28)) +>v12 : Symbol(v12, Decl(collisionArgumentsInType.ts, 1, 3)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 1, 10)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 1, 28)) var v2: { ->v2 : Symbol(v2, Decl(collisionArgumentsInType.ts, 3, 3)) +>v2 : Symbol(v2, Decl(collisionArgumentsInType.ts, 2, 3)) (arguments: number, ...restParameters); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 4, 5)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 4, 23)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 3, 5)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 3, 23)) new (arguments: number, ...restParameters); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 5, 9)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 5, 27)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 4, 9)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 4, 27)) foo(arguments: number, ...restParameters); // no error - no code gen ->foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 5, 47)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 6, 8)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 6, 26)) +>foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 4, 47)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 5, 8)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 5, 26)) prop: (arguments: number, ...restParameters) => void; // no error - no code gen ->prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 6, 46)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 7, 11)) ->restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 7, 29)) +>prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 5, 46)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 6, 11)) +>restParameters : Symbol(restParameters, Decl(collisionArgumentsInType.ts, 6, 29)) } var v21: { ->v21 : Symbol(v21, Decl(collisionArgumentsInType.ts, 9, 3)) +>v21 : Symbol(v21, Decl(collisionArgumentsInType.ts, 8, 3)) (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 10, 5)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 10, 15)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 9, 5)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 9, 15)) new (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 11, 9)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 11, 19)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 10, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 10, 19)) foo(i: number, ...arguments); // no error - no code gen ->foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 11, 34)) ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 12, 8)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 12, 18)) +>foo : Symbol(foo, Decl(collisionArgumentsInType.ts, 10, 34)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 11, 8)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 11, 18)) prop: (i: number, ...arguments) => void; // no error - no code gen ->prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 12, 33)) ->i : Symbol(i, Decl(collisionArgumentsInType.ts, 13, 11)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 13, 21)) +>prop : Symbol(prop, Decl(collisionArgumentsInType.ts, 11, 33)) +>i : Symbol(i, Decl(collisionArgumentsInType.ts, 12, 11)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInType.ts, 12, 21)) } diff --git a/tests/baselines/reference/collisionArgumentsInType.types b/tests/baselines/reference/collisionArgumentsInType.types index 7b4c8983b4c..a8096e2e7f5 100644 --- a/tests/baselines/reference/collisionArgumentsInType.types +++ b/tests/baselines/reference/collisionArgumentsInType.types @@ -1,7 +1,4 @@ === tests/cases/compiler/collisionArgumentsInType.ts === -"use strict"; ->"use strict" : "use strict" - var v1: (i: number, ...arguments) => void; // no error - no code gen >v1 : (i: number, ...arguments: any[]) => void >i : number diff --git a/tests/baselines/reference/collisionArgumentsInterfaceMembers.js b/tests/baselines/reference/collisionArgumentsInterfaceMembers.js index 34530ca2c72..a55e112b603 100644 --- a/tests/baselines/reference/collisionArgumentsInterfaceMembers.js +++ b/tests/baselines/reference/collisionArgumentsInterfaceMembers.js @@ -1,5 +1,4 @@ //// [collisionArgumentsInterfaceMembers.ts] -"use strict"; // call interface i1 { (i: number, ...arguments); // no error - no code gen @@ -30,4 +29,3 @@ interface i3 { } //// [collisionArgumentsInterfaceMembers.js] -"use strict"; diff --git a/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols b/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols index a7e14b5959e..f0a82bec521 100644 --- a/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols +++ b/tests/baselines/reference/collisionArgumentsInterfaceMembers.symbols @@ -1,64 +1,63 @@ === tests/cases/compiler/collisionArgumentsInterfaceMembers.ts === -"use strict"; // call interface i1 { ->i1 : Symbol(i1, Decl(collisionArgumentsInterfaceMembers.ts, 0, 13)) +>i1 : Symbol(i1, Decl(collisionArgumentsInterfaceMembers.ts, 0, 0)) (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 3, 5)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 3, 15)) +>i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 2, 5)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 2, 15)) } interface i12 { ->i12 : Symbol(i12, Decl(collisionArgumentsInterfaceMembers.ts, 4, 1)) +>i12 : Symbol(i12, Decl(collisionArgumentsInterfaceMembers.ts, 3, 1)) (arguments: number, ...rest); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 6, 5)) ->rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 6, 23)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 5, 5)) +>rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 5, 23)) } interface i1NoError { ->i1NoError : Symbol(i1NoError, Decl(collisionArgumentsInterfaceMembers.ts, 7, 1)) +>i1NoError : Symbol(i1NoError, Decl(collisionArgumentsInterfaceMembers.ts, 6, 1)) (arguments: number); // no error ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 9, 5)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 8, 5)) } // new interface i2 { ->i2 : Symbol(i2, Decl(collisionArgumentsInterfaceMembers.ts, 10, 1)) +>i2 : Symbol(i2, Decl(collisionArgumentsInterfaceMembers.ts, 9, 1)) new (i: number, ...arguments); // no error - no code gen ->i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 14, 9)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 14, 19)) +>i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 13, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 13, 19)) } interface i21 { ->i21 : Symbol(i21, Decl(collisionArgumentsInterfaceMembers.ts, 15, 1)) +>i21 : Symbol(i21, Decl(collisionArgumentsInterfaceMembers.ts, 14, 1)) new (arguments: number, ...rest); // no error - no code gen ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 17, 9)) ->rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 17, 27)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 16, 9)) +>rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 16, 27)) } interface i2NoError { ->i2NoError : Symbol(i2NoError, Decl(collisionArgumentsInterfaceMembers.ts, 18, 1)) +>i2NoError : Symbol(i2NoError, Decl(collisionArgumentsInterfaceMembers.ts, 17, 1)) new (arguments: number); // no error ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 20, 9)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 19, 9)) } // method interface i3 { ->i3 : Symbol(i3, Decl(collisionArgumentsInterfaceMembers.ts, 21, 1)) +>i3 : Symbol(i3, Decl(collisionArgumentsInterfaceMembers.ts, 20, 1)) foo(i: number, ...arguments); // no error - no code gen ->foo : Symbol(i3.foo, Decl(collisionArgumentsInterfaceMembers.ts, 24, 14)) ->i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 25, 8)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 25, 18)) +>foo : Symbol(i3.foo, Decl(collisionArgumentsInterfaceMembers.ts, 23, 14)) +>i : Symbol(i, Decl(collisionArgumentsInterfaceMembers.ts, 24, 8)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 24, 18)) foo1(arguments: number, ...rest); // no error - no code gen ->foo1 : Symbol(i3.foo1, Decl(collisionArgumentsInterfaceMembers.ts, 25, 33)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 26, 9)) ->rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 26, 27)) +>foo1 : Symbol(i3.foo1, Decl(collisionArgumentsInterfaceMembers.ts, 24, 33)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 25, 9)) +>rest : Symbol(rest, Decl(collisionArgumentsInterfaceMembers.ts, 25, 27)) fooNoError(arguments: number); // no error ->fooNoError : Symbol(i3.fooNoError, Decl(collisionArgumentsInterfaceMembers.ts, 26, 37)) ->arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 27, 15)) +>fooNoError : Symbol(i3.fooNoError, Decl(collisionArgumentsInterfaceMembers.ts, 25, 37)) +>arguments : Symbol(arguments, Decl(collisionArgumentsInterfaceMembers.ts, 26, 15)) } diff --git a/tests/baselines/reference/collisionArgumentsInterfaceMembers.types b/tests/baselines/reference/collisionArgumentsInterfaceMembers.types index 3563a25b0bd..6edb0a7ebed 100644 --- a/tests/baselines/reference/collisionArgumentsInterfaceMembers.types +++ b/tests/baselines/reference/collisionArgumentsInterfaceMembers.types @@ -1,7 +1,4 @@ === tests/cases/compiler/collisionArgumentsInterfaceMembers.ts === -"use strict"; ->"use strict" : "use strict" - // call interface i1 { >i1 : i1 diff --git a/tests/cases/compiler/collisionArgumentsFunction.ts b/tests/cases/compiler/collisionArgumentsFunction.ts index d5136d9169a..b90dee9ec11 100644 --- a/tests/cases/compiler/collisionArgumentsFunction.ts +++ b/tests/cases/compiler/collisionArgumentsFunction.ts @@ -36,12 +36,9 @@ function f4NoError(arguments: any) { // no error var arguments: any; // No error } -namespace strict { - "use strict"; - declare function f5(arguments: number, ...rest); // no codegen no error - declare function f5(arguments: string, ...rest); // no codegen no error - declare function f52(i: number, ...arguments); // no codegen no error - declare function f52(i: string, ...arguments); // no codegen no error - declare function f6(arguments: number); // no codegen no error - declare function f6(arguments: string); // no codegen no error -} \ No newline at end of file +declare function f5(arguments: number, ...rest); // no codegen no error +declare function f5(arguments: string, ...rest); // no codegen no error +declare function f52(i: number, ...arguments); // no codegen no error +declare function f52(i: string, ...arguments); // no codegen no error +declare function f6(arguments: number); // no codegen no error +declare function f6(arguments: string); // no codegen no error \ No newline at end of file diff --git a/tests/cases/compiler/collisionArgumentsInType.ts b/tests/cases/compiler/collisionArgumentsInType.ts index 13785ef669d..c9354ba0bae 100644 --- a/tests/cases/compiler/collisionArgumentsInType.ts +++ b/tests/cases/compiler/collisionArgumentsInType.ts @@ -1,4 +1,3 @@ -"use strict"; var v1: (i: number, ...arguments) => void; // no error - no code gen var v12: (arguments: number, ...restParameters) => void; // no error - no code gen var v2: { diff --git a/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts b/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts index 87b6b4503ac..bfb280116e4 100644 --- a/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts +++ b/tests/cases/compiler/collisionArgumentsInterfaceMembers.ts @@ -1,4 +1,3 @@ -"use strict"; // call interface i1 { (i: number, ...arguments); // no error - no code gen From f2b7606b123945b84d799150e4be279554712aaa Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 2 May 2017 12:49:34 -0700 Subject: [PATCH 041/282] Switch to __await sentinel, better support for return values --- src/compiler/transformers/esnext.ts | 125 +++++++------ ...ter.asyncGenerators.classMethods.es2015.js | 165 ++++++++-------- ...mitter.asyncGenerators.classMethods.es5.js | 177 +++++++++--------- ...cGenerators.functionDeclarations.es2015.js | 135 +++++++------ ...syncGenerators.functionDeclarations.es5.js | 147 +++++++-------- ...ncGenerators.functionExpressions.es2015.js | 135 +++++++------ ...asyncGenerators.functionExpressions.es5.js | 147 +++++++-------- ...cGenerators.objectLiteralMethods.es2015.js | 135 +++++++------ ...syncGenerators.objectLiteralMethods.es5.js | 147 +++++++-------- .../reference/emitter.forAwait.es2015.js | 50 +++-- .../reference/emitter.forAwait.es5.js | 110 +++++------ 11 files changed, 700 insertions(+), 773 deletions(-) diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 29cdbad5e7f..133272afc3a 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -106,15 +106,11 @@ namespace ts { } } - function visitAwaitExpression(node: AwaitExpression) { + function visitAwaitExpression(node: AwaitExpression): Expression { if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { - const expression = visitNode(node.expression, visitor, isExpression); return setOriginalNode( setTextRange( - createYield( - /*asteriskToken*/ undefined, - createArrayLiteral([createLiteral("await"), expression]) - ), + createYield(createAwaitHelper(context, visitNode(node.expression, visitor, isExpression))), /*location*/ node ), node @@ -124,21 +120,26 @@ namespace ts { } function visitYieldExpression(node: YieldExpression) { - if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { + if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator && node.asteriskToken) { const expression = visitNode(node.expression, visitor, isExpression); - const delegator = node.asteriskToken && updateYield( - node, - node.asteriskToken, - createAsyncDelegatorHelper(context, expression, expression) - ); - return updateYield( - node, - /*asteriskToken*/ undefined, - createArrayLiteral( - delegator ? [createLiteral("await"), delegator] : - expression ? [createLiteral("yield"), expression] : - [createLiteral("yield")] - ) + return setOriginalNode( + setTextRange( + createYield( + createAwaitHelper(context, + updateYield( + node, + node.asteriskToken, + createAsyncDelegatorHelper( + context, + createAsyncValuesHelper(context, expression, expression), + expression + ) + ) + ) + ), + node + ), + node ); } return visitEachChild(node, visitor, context); @@ -350,6 +351,10 @@ namespace ts { ); } + function awaitAsYield(expression: Expression) { + return createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & FunctionFlags.Generator ? createAwaitHelper(context, expression) : expression); + } + function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement) { const expression = visitNode(node.expression, visitor, isExpression); const iterator = isIdentifier(expression) ? getGeneratedNameForNode(expression) : createTempVariable(/*recordTempVariable*/ undefined); @@ -357,16 +362,11 @@ namespace ts { const errorRecord = createUniqueName("e"); const catchVariable = getGeneratedNameForNode(errorRecord); const returnMethod = createTempVariable(/*recordTempVariable*/ undefined); - const values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - const next = createYield( - /*asteriskToken*/ undefined, - enclosingFunctionFlags & FunctionFlags.Generator - ? createArrayLiteral([ - createLiteral("await"), - createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []) - ]) - : createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []) - ); + const callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + const callNext = createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []); + const getDone = createPropertyAccess(result, "done"); + const getValue = createPropertyAccess(result, "value"); + const callReturn = createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); @@ -377,16 +377,19 @@ namespace ts { /*initializer*/ setEmitFlags( setTextRange( createVariableDeclarationList([ - setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - createVariableDeclaration(result, /*type*/ undefined, next) + setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + createVariableDeclaration(result) ]), node.expression ), EmitFlags.NoHoisting ), - /*condition*/ createLogicalNot(createPropertyAccess(result, "done")), - /*incrementor*/ createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, createPropertyAccess(result, "value")) + /*condition*/ createComma( + createAssignment(result, awaitAsYield(callNext)), + createLogicalNot(getDone) + ), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue)) ), /*location*/ node ), @@ -424,26 +427,14 @@ namespace ts { createLogicalAnd( createLogicalAnd( result, - createLogicalNot( - createPropertyAccess(result, "done") - ) + createLogicalNot(getDone) ), createAssignment( returnMethod, createPropertyAccess(iterator, "return") ) ), - createStatement( - createYield( - /*asteriskToken*/ undefined, - enclosingFunctionFlags & FunctionFlags.Generator - ? createArrayLiteral([ - createLiteral("await"), - createFunctionCall(returnMethod, iterator, []) - ]) - : createFunctionCall(returnMethod, iterator, []) - ) - ) + createStatement(awaitAsYield(callReturn)) ), EmitFlags.SingleLine ) @@ -883,27 +874,39 @@ namespace ts { ); } + const awaitHelper: EmitHelper = { + name: "typescript:await", + scoped: false, + text: ` + var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } + ` + }; + + function createAwaitHelper(context: TransformationContext, expression: Expression) { + context.requestEmitHelper(awaitHelper); + return createCall(createIdentifier("__await"), /*typeArguments*/ undefined, [expression]); + } + const asyncGeneratorHelper: EmitHelper = { name: "typescript:asyncGenerator", scoped: false, text: ` var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; ` }; function createAsyncGeneratorHelper(context: TransformationContext, generatorFunc: FunctionExpression) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function @@ -925,16 +928,16 @@ namespace ts { scoped: false, text: ` var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; ` }; function createAsyncDelegatorHelper(context: TransformationContext, expression: Expression, location?: TextRange) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return setTextRange( createCall( getHelperName("__asyncDelegator"), diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js index 58a4306c113..2a0ca50a97b 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js @@ -61,18 +61,17 @@ class C9 extends B9 { //// [C1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C1 { f() { @@ -81,143 +80,137 @@ class C1 { } } //// [C2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C2 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield"]; + const x = yield; }); } } //// [C3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C3 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield", 1]; + const x = yield 1; }); } } //// [C4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C4 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", yield* __asyncDelegator([1])]; + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); } } //// [C5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; class C5 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); } } //// [C6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C6 { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", 1]; + const x = yield __await(1); }); } } //// [C7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C7 { f() { @@ -227,18 +220,17 @@ class C7 { } } //// [C8.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class C8 { g() { @@ -250,18 +242,17 @@ class C8 { } } //// [C9.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; class B9 { g() { } diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js index cb4418936be..a72f1dd27c5 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js @@ -88,18 +88,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C1 = (function () { function C1() { @@ -141,18 +140,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C2 = (function () { function C2() { @@ -162,7 +160,7 @@ var C2 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -200,18 +198,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C3 = (function () { function C3() { @@ -221,7 +218,7 @@ var C3 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -259,28 +256,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -301,9 +297,9 @@ var C4 = (function () { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -341,29 +337,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -383,16 +378,16 @@ var C5 = (function () { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + }); }); })())))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -430,18 +425,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C6 = (function () { function C6() { @@ -451,7 +445,7 @@ var C6 = (function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -489,18 +483,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C7 = (function () { function C7() { @@ -542,18 +535,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var C8 = (function () { function C8() { @@ -608,18 +600,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var B9 = (function () { function B9() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js index a3a6baf319a..b25f69297d3 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js @@ -30,151 +30,144 @@ async function * f7() { //// [F1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f1() { return __asyncGenerator(this, arguments, function* f1_1() { }); } //// [F2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f2() { return __asyncGenerator(this, arguments, function* f2_1() { - const x = yield ["yield"]; + const x = yield; }); } //// [F3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function* f3_1() { - const x = yield ["yield", 1]; + const x = yield 1; }); } //// [F4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f4() { return __asyncGenerator(this, arguments, function* f4_1() { - const x = yield ["await", yield* __asyncDelegator([1])]; + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); } //// [F5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; function f5() { return __asyncGenerator(this, arguments, function* f5_1() { - const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); } //// [F6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f6() { return __asyncGenerator(this, arguments, function* f6_1() { - const x = yield ["await", 1]; + const x = yield __await(1); }); } //// [F7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f7() { return __asyncGenerator(this, arguments, function* f7_1() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js index 1e75fb61c2f..87d5f1a2b01 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js @@ -57,18 +57,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f1() { return __asyncGenerator(this, arguments, function f1_1() { @@ -105,25 +104,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f2() { return __asyncGenerator(this, arguments, function f2_1() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -159,25 +157,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function f3_1() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -213,28 +210,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -252,9 +248,9 @@ function f4() { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -290,29 +286,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -329,16 +324,16 @@ function f5() { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + }); }); })())))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -374,25 +369,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f6() { return __asyncGenerator(this, arguments, function f6_1() { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -428,18 +422,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f7() { return __asyncGenerator(this, arguments, function f7_1() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js index 475445b2f0a..78909a55ab0 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js @@ -30,151 +30,144 @@ const f7 = async function * () { //// [F1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f1 = function () { return __asyncGenerator(this, arguments, function* () { }); }; //// [F2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f2 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["yield"]; + const x = yield; }); }; //// [F3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f3 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["yield", 1]; + const x = yield 1; }); }; //// [F4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f4 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["await", yield* __asyncDelegator([1])]; + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); }; //// [F5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; const f5 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); }; //// [F6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f6 = function () { return __asyncGenerator(this, arguments, function* () { - const x = yield ["await", 1]; + const x = yield __await(1); }); }; //// [F7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const f7 = function () { return __asyncGenerator(this, arguments, function* () { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js index bb94d82d7b6..9f4811d8af9 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js @@ -57,18 +57,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f1 = function () { return __asyncGenerator(this, arguments, function () { @@ -105,25 +104,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f2 = function () { return __asyncGenerator(this, arguments, function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -159,25 +157,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f3 = function () { return __asyncGenerator(this, arguments, function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -213,28 +210,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -252,9 +248,9 @@ var f4 = function () { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -290,29 +286,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -329,16 +324,16 @@ var f5 = function () { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + }); }); })())))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -374,25 +369,24 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f6 = function () { return __asyncGenerator(this, arguments, function () { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -428,18 +422,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var f7 = function () { return __asyncGenerator(this, arguments, function () { diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js index eedbfaf5998..902197651be 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js @@ -44,18 +44,17 @@ const o7 = { //// [O1.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o1 = { f() { @@ -64,143 +63,137 @@ const o1 = { } }; //// [O2.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o2 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield"]; + const x = yield; }); } }; //// [O3.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o3 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["yield", 1]; + const x = yield 1; }); } }; //// [O4.js] -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o4 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", yield* __asyncDelegator([1])]; + const x = yield __await(yield* __asyncDelegator(__asyncValues([1]))); }); } }; //// [O5.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; const o5 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", yield* __asyncDelegator((function () { return __asyncGenerator(this, arguments, function* () { yield ["yield", 1]; }); })())]; + const x = yield __await(yield* __asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function* () { yield 1; }); })()))); }); } }; //// [O6.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o6 = { f() { return __asyncGenerator(this, arguments, function* f_1() { - const x = yield ["await", 1]; + const x = yield __await(1); }); } }; //// [O7.js] +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; const o7 = { f() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js index c108d49a26f..34d970afdbe 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js @@ -71,18 +71,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o1 = { f: function () { @@ -121,18 +120,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o2 = { f: function () { @@ -140,7 +138,7 @@ var o2 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield"]]; + case 0: return [4 /*yield*/]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -177,18 +175,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o3 = { f: function () { @@ -196,7 +193,7 @@ var o3 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -233,28 +230,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } -}; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; @@ -273,9 +269,9 @@ var o4 = { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator([1]))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -312,29 +308,28 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } -}; -var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i, f; - return o = __asyncValues(o), i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (b) { return (f = !f) ? { value: ["await", new Promise(function(r) { r(o[n](b)); })], done: n === "return" } : b.done ? b : { value: ["yield", b.value], done: false }; }; } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __asyncValues = (this && this.__asyncIterator) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; + return i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } +}; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); @@ -352,16 +347,16 @@ var o5 = { return __generator(this, function (_b) { switch (_b.label) { case 0: - _a = ["await"]; - return [5 /*yield**/, __values(__asyncDelegator((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + _a = __await; + return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["yield", 1]]; + case 0: return [4 /*yield*/, 1]; case 1: _a.sent(); return [2 /*return*/]; } - }); }); })()))]; - case 1: return [4 /*yield*/, _a.concat([_b.sent()])]; + }); }); })())))]; + case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; case 2: x = _b.sent(); return [2 /*return*/]; @@ -398,18 +393,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o6 = { f: function () { @@ -417,7 +411,7 @@ var o6 = { var x; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, ["await", 1]]; + case 0: return [4 /*yield*/, __await(1)]; case 1: x = _a.sent(); return [2 /*return*/]; @@ -454,18 +448,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var o7 = { f: function () { diff --git a/tests/baselines/reference/emitter.forAwait.es2015.js b/tests/baselines/reference/emitter.forAwait.es2015.js index 4bba2d06dcc..d88ed8d1a06 100644 --- a/tests/baselines/reference/emitter.forAwait.es2015.js +++ b/tests/baselines/reference/emitter.forAwait.es2015.js @@ -43,8 +43,8 @@ function f1() { return __awaiter(this, void 0, void 0, function* () { let y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield y_1.next(); !y_1_1.done; y_1_1 = yield y_1.next()) { - const x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield y_1.next(), !y_1_1.done;) { + const x = yield y_1_1.value; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } @@ -75,8 +75,8 @@ function f2() { return __awaiter(this, void 0, void 0, function* () { let x, y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield y_1.next(); !y_1_1.done; y_1_1 = yield y_1.next()) { - x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield y_1.next(), !y_1_1.done;) { + x = yield y_1_1.value; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } @@ -95,31 +95,30 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function* f3_1() { let y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield ["await", y_1.next()]; !y_1_1.done; y_1_1 = yield ["await", y_1.next()]) { - const x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield __await(y_1.next()), !y_1_1.done;) { + const x = yield __await(y_1_1.value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield ["await", _a.call(y_1)]; + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield __await(_a.call(y_1)); } finally { if (e_1) throw e_1.error; } } @@ -132,31 +131,30 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f4() { return __asyncGenerator(this, arguments, function* f4_1() { let x, y; try { - for (var y_1 = __asyncValues(y), y_1_1 = yield ["await", y_1.next()]; !y_1_1.done; y_1_1 = yield ["await", y_1.next()]) { - x = y_1_1.value; + for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield __await(y_1.next()), !y_1_1.done;) { + x = yield __await(y_1_1.value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield ["await", _a.call(y_1)]; + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield __await(_a.call(y_1)); } finally { if (e_1) throw e_1.error; } } diff --git a/tests/baselines/reference/emitter.forAwait.es5.js b/tests/baselines/reference/emitter.forAwait.es5.js index 09b73ed21f0..fc8f5fd321d 100644 --- a/tests/baselines/reference/emitter.forAwait.es5.js +++ b/tests/baselines/reference/emitter.forAwait.es5.js @@ -74,18 +74,15 @@ function f1() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, y_1.next()]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, y_1.next()]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, y_1.next()]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, y_1_1.value]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -157,18 +154,15 @@ function f2() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, y_1.next()]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, y_1.next()]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, y_1.next()]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, y_1_1.value]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -224,18 +218,17 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f3() { return __asyncGenerator(this, arguments, function f3_1() { @@ -245,18 +238,15 @@ function f3() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, ["await", y_1.next()]]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, __await(y_1.next())]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, ["await", y_1.next()]]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, __await(y_1_1.value)]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -265,7 +255,7 @@ function f3() { case 7: _b.trys.push([7, , 10, 11]); if (!(y_1_1 && !y_1_1.done && (_a = y_1.return))) return [3 /*break*/, 9]; - return [4 /*yield*/, ["await", _a.call(y_1)]]; + return [4 /*yield*/, __await(_a.call(y_1))]; case 8: _b.sent(); _b.label = 9; @@ -312,18 +302,17 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + 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); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function f4() { return __asyncGenerator(this, arguments, function f4_1() { @@ -333,18 +322,15 @@ function f4() { case 0: _b.trys.push([0, 6, 7, 12]); y_1 = __asyncValues(y); - return [4 /*yield*/, ["await", y_1.next()]]; - case 1: - y_1_1 = _b.sent(); - _b.label = 2; + _b.label = 1; + case 1: return [4 /*yield*/, __await(y_1.next())]; case 2: - if (!!y_1_1.done) return [3 /*break*/, 5]; - x = y_1_1.value; - _b.label = 3; - case 3: return [4 /*yield*/, ["await", y_1.next()]]; - case 4: - y_1_1 = _b.sent(); - return [3 /*break*/, 2]; + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, __await(y_1_1.value)]; + case 3: + x = _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _b.sent(); @@ -353,7 +339,7 @@ function f4() { case 7: _b.trys.push([7, , 10, 11]); if (!(y_1_1 && !y_1_1.done && (_a = y_1.return))) return [3 /*break*/, 9]; - return [4 /*yield*/, ["await", _a.call(y_1)]]; + return [4 /*yield*/, __await(_a.call(y_1))]; case 8: _b.sent(); _b.label = 9; From f61ec7fb604a897e2bb581fc8623c39d84ff71f0 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 2 May 2017 13:36:01 -0700 Subject: [PATCH 042/282] Declare synthetic var for class extends expression Classes that extend expressions will get a synthetic var declaration for the expression. This is required for classes that extend an expression that return an intersection type. --- src/compiler/checker.ts | 2 +- src/compiler/declarationEmitter.ts | 83 +++++++++++++++++++----------- 2 files changed, 55 insertions(+), 30 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 18e57303c12..dac3dce3b32 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22645,7 +22645,7 @@ namespace ts { const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); resolveBaseTypesOfClass(classType); const baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { + if (!baseType.symbol && !(baseType.flags & TypeFlags.Intersection)) { writer.reportIllegalExtends(); } getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 2bd8d5971fb..7251fec169f 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -594,12 +594,11 @@ namespace ts { emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName(): string { - const baseName = "_default"; + function getExportTempVariableName(baseName: string): string { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -613,24 +612,31 @@ namespace ts { } } + function emitTempVariableDeclaration(expr: Expression, baseName: string, diagnostic: SymbolAccessibilityDiagnostic): string { + const tempVarName = getExportTempVariableName(baseName); + if (!noDeclare) { + write("declare "); + } + write("var "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = () => diagnostic; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); + write(";"); + writeLine(); + return tempVarName; + } + function emitExportAssignment(node: ExportAssignment) { if (node.expression.kind === SyntaxKind.Identifier) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - const tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); - write(";"); - writeLine(); + const tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -644,13 +650,6 @@ namespace ts { // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - - function getDefaultExportAccessibilityDiagnostic(): SymbolAccessibilityDiagnostic { - return { - diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node: Declaration) { @@ -1113,7 +1112,11 @@ namespace ts { else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); + resolver.writeBaseConstructorTypeOfClass( + enclosingDeclaration as ClassLikeDeclaration, + enclosingDeclaration, + TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, + writer); errorNameNode = undefined; } @@ -1151,21 +1154,39 @@ namespace ts { } } + const prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + const baseTypeNode = getClassExtendsHeritageClauseElement(node); + let tempVarName: string; + if (isNonNullExpression(baseTypeNode)) { + tempVarName = emitTempVariableDeclaration(baseTypeNode.expression, `_${node.name.text}_intersection_base`, { + diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }); + } + emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (hasModifier(node, ModifierFlags.Abstract)) { write("abstract "); } - write("class "); writeTextOfNode(currentText, node.name); - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (isNonNullExpression(baseTypeNode)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + } } emitHeritageClause(node.name, getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); @@ -1201,6 +1222,10 @@ namespace ts { enclosingDeclaration = prevEnclosingDeclaration; } + function isNonNullExpression(node: ExpressionWithTypeArguments) { + return node && !isEntityNameExpression(node.expression) && node.expression.kind !== SyntaxKind.NullKeyword; + } + function emitPropertyDeclaration(node: Declaration) { if (hasDynamicName(node)) { return; From bdb90deacb471a8aca50393f1001426b7a475234 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 2 May 2017 13:38:53 -0700 Subject: [PATCH 043/282] Update baselines --- .../declarationEmitExpressionInExtends2.js | 3 +- ...arationEmitExpressionInExtends3.errors.txt | 4 +- ...arationEmitExpressionInExtends4.errors.txt | 11 +-- ...xportClassExtendingIntersection.errors.txt | 39 --------- .../exportClassExtendingIntersection.js | 7 ++ .../exportClassExtendingIntersection.symbols | 79 +++++++++++++++++ .../exportClassExtendingIntersection.types | 84 +++++++++++++++++++ .../reference/mixinAccessModifiers.errors.txt | 20 +---- .../reference/mixinAccessModifiers.js | 63 ++++++++++++++ 9 files changed, 242 insertions(+), 68 deletions(-) delete mode 100644 tests/baselines/reference/exportClassExtendingIntersection.errors.txt create mode 100644 tests/baselines/reference/exportClassExtendingIntersection.symbols create mode 100644 tests/baselines/reference/exportClassExtendingIntersection.types diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends2.js b/tests/baselines/reference/declarationEmitExpressionInExtends2.js index 301d935a1db..ed3bc9d96f3 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends2.js +++ b/tests/baselines/reference/declarationEmitExpressionInExtends2.js @@ -45,5 +45,6 @@ declare class C { y: U; } declare function getClass(c: T): typeof C; -declare class MyClass extends C { +declare var _MyClass_intersection_base: typeof C; +declare class MyClass extends _MyClass_intersection_base { } diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt b/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt index 636085215ac..4864a3bcdc2 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt +++ b/tests/baselines/reference/declarationEmitExpressionInExtends3.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/declarationEmitExpressionInExtends3.ts(28,30): error TS4020: 'extends' clause of exported class 'MyClass' has or is using private name 'LocalClass'. -tests/cases/compiler/declarationEmitExpressionInExtends3.ts(36,31): error TS4020: 'extends' clause of exported class 'MyClass3' has or is using private name 'LocalInterface'. +tests/cases/compiler/declarationEmitExpressionInExtends3.ts(36,75): error TS4020: 'extends' clause of exported class 'MyClass3' has or is using private name 'LocalInterface'. ==== tests/cases/compiler/declarationEmitExpressionInExtends3.ts (2 errors) ==== @@ -41,7 +41,7 @@ tests/cases/compiler/declarationEmitExpressionInExtends3.ts(36,31): error TS4020 export class MyClass3 extends getExportedClass(undefined) { // Error LocalInterface is inaccisble - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~ !!! error TS4020: 'extends' clause of exported class 'MyClass3' has or is using private name 'LocalInterface'. } diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt b/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt index b2e3eb58d54..54905212836 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt +++ b/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt @@ -1,13 +1,12 @@ tests/cases/compiler/declarationEmitExpressionInExtends4.ts(1,10): error TS4060: Return type of exported function has or is using private name 'D'. -tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,7): error TS4093: 'extends' clause of exported class 'C' refers to a type whose name cannot be referenced. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,17): error TS2315: Type 'D' is not generic. -tests/cases/compiler/declarationEmitExpressionInExtends4.ts(9,7): error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. +tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,17): error TS4020: 'extends' clause of exported class 'C' has or is using private name 'D'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(9,18): error TS2304: Cannot find name 'SomeUndefinedFunction'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS2304: Cannot find name 'SomeUndefinedFunction'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS4020: 'extends' clause of exported class 'C3' has or is using private name 'SomeUndefinedFunction'. -==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (7 errors) ==== +==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (6 errors) ==== function getSomething() { ~~~~~~~~~~~~ !!! error TS4060: Return type of exported function has or is using private name 'D'. @@ -15,16 +14,14 @@ tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS4020 } class C extends getSomething() { - ~ -!!! error TS4093: 'extends' clause of exported class 'C' refers to a type whose name cannot be referenced. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2315: Type 'D' is not generic. + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS4020: 'extends' clause of exported class 'C' has or is using private name 'D'. } class C2 extends SomeUndefinedFunction() { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'SomeUndefinedFunction'. diff --git a/tests/baselines/reference/exportClassExtendingIntersection.errors.txt b/tests/baselines/reference/exportClassExtendingIntersection.errors.txt deleted file mode 100644 index eb94869fdc2..00000000000 --- a/tests/baselines/reference/exportClassExtendingIntersection.errors.txt +++ /dev/null @@ -1,39 +0,0 @@ -tests/cases/compiler/FinalClass.ts(4,14): error TS4093: 'extends' clause of exported class 'MyExtendedClass' refers to a type whose name cannot be referenced. - - -==== tests/cases/compiler/BaseClass.ts (0 errors) ==== - export type Constructor = new (...args: any[]) => T; - - export class MyBaseClass { - baseProperty: string; - constructor(value: T) {} - } -==== tests/cases/compiler/MixinClass.ts (0 errors) ==== - import { Constructor, MyBaseClass } from './BaseClass'; - - export interface MyMixin { - mixinProperty: string; - } - - export function MyMixin>>(base: T): T & Constructor { - return class extends base { - mixinProperty: string; - } - } -==== tests/cases/compiler/FinalClass.ts (1 errors) ==== - import { MyBaseClass } from './BaseClass'; - import { MyMixin } from './MixinClass'; - - export class MyExtendedClass extends MyMixin(MyBaseClass) { - ~~~~~~~~~~~~~~~ -!!! error TS4093: 'extends' clause of exported class 'MyExtendedClass' refers to a type whose name cannot be referenced. - extendedClassProperty: number; - } -==== tests/cases/compiler/Main.ts (0 errors) ==== - import { MyExtendedClass } from './FinalClass'; - import { MyMixin } from './MixinClass'; - - const myExtendedClass = new MyExtendedClass('string'); - - const AnotherMixedClass = MyMixin(MyExtendedClass); - \ No newline at end of file diff --git a/tests/baselines/reference/exportClassExtendingIntersection.js b/tests/baselines/reference/exportClassExtendingIntersection.js index 2309a9af9b6..cfb3fd66842 100644 --- a/tests/baselines/reference/exportClassExtendingIntersection.js +++ b/tests/baselines/reference/exportClassExtendingIntersection.js @@ -111,4 +111,11 @@ export interface MyMixin { mixinProperty: string; } export declare function MyMixin>>(base: T): T & Constructor; +//// [FinalClass.d.ts] +import { MyBaseClass } from './BaseClass'; +import { MyMixin } from './MixinClass'; +declare var _MyExtendedClass_intersection_base: typeof MyBaseClass & (new (...args: any[]) => MyMixin); +export declare class MyExtendedClass extends _MyExtendedClass_intersection_base { + extendedClassProperty: number; +} //// [Main.d.ts] diff --git a/tests/baselines/reference/exportClassExtendingIntersection.symbols b/tests/baselines/reference/exportClassExtendingIntersection.symbols new file mode 100644 index 00000000000..b22febb7d72 --- /dev/null +++ b/tests/baselines/reference/exportClassExtendingIntersection.symbols @@ -0,0 +1,79 @@ +=== tests/cases/compiler/BaseClass.ts === +export type Constructor = new (...args: any[]) => T; +>Constructor : Symbol(Constructor, Decl(BaseClass.ts, 0, 0)) +>T : Symbol(T, Decl(BaseClass.ts, 0, 24)) +>args : Symbol(args, Decl(BaseClass.ts, 0, 34)) +>T : Symbol(T, Decl(BaseClass.ts, 0, 24)) + +export class MyBaseClass { +>MyBaseClass : Symbol(MyBaseClass, Decl(BaseClass.ts, 0, 55)) +>T : Symbol(T, Decl(BaseClass.ts, 2, 25)) + + baseProperty: string; +>baseProperty : Symbol(MyBaseClass.baseProperty, Decl(BaseClass.ts, 2, 29)) + + constructor(value: T) {} +>value : Symbol(value, Decl(BaseClass.ts, 4, 16)) +>T : Symbol(T, Decl(BaseClass.ts, 2, 25)) +} +=== tests/cases/compiler/MixinClass.ts === +import { Constructor, MyBaseClass } from './BaseClass'; +>Constructor : Symbol(Constructor, Decl(MixinClass.ts, 0, 8)) +>MyBaseClass : Symbol(MyBaseClass, Decl(MixinClass.ts, 0, 21)) + +export interface MyMixin { +>MyMixin : Symbol(MyMixin, Decl(MixinClass.ts, 0, 55), Decl(MixinClass.ts, 4, 1)) + + mixinProperty: string; +>mixinProperty : Symbol(MyMixin.mixinProperty, Decl(MixinClass.ts, 2, 26)) +} + +export function MyMixin>>(base: T): T & Constructor { +>MyMixin : Symbol(MyMixin, Decl(MixinClass.ts, 0, 55), Decl(MixinClass.ts, 4, 1)) +>T : Symbol(T, Decl(MixinClass.ts, 6, 24)) +>Constructor : Symbol(Constructor, Decl(MixinClass.ts, 0, 8)) +>MyBaseClass : Symbol(MyBaseClass, Decl(MixinClass.ts, 0, 21)) +>base : Symbol(base, Decl(MixinClass.ts, 6, 65)) +>T : Symbol(T, Decl(MixinClass.ts, 6, 24)) +>T : Symbol(T, Decl(MixinClass.ts, 6, 24)) +>Constructor : Symbol(Constructor, Decl(MixinClass.ts, 0, 8)) +>MyMixin : Symbol(MyMixin, Decl(MixinClass.ts, 0, 55), Decl(MixinClass.ts, 4, 1)) + + return class extends base { +>base : Symbol(base, Decl(MixinClass.ts, 6, 65)) + + mixinProperty: string; +>mixinProperty : Symbol((Anonymous class).mixinProperty, Decl(MixinClass.ts, 7, 31)) + } +} +=== tests/cases/compiler/FinalClass.ts === +import { MyBaseClass } from './BaseClass'; +>MyBaseClass : Symbol(MyBaseClass, Decl(FinalClass.ts, 0, 8)) + +import { MyMixin } from './MixinClass'; +>MyMixin : Symbol(MyMixin, Decl(FinalClass.ts, 1, 8)) + +export class MyExtendedClass extends MyMixin(MyBaseClass) { +>MyExtendedClass : Symbol(MyExtendedClass, Decl(FinalClass.ts, 1, 39)) +>MyMixin : Symbol(MyMixin, Decl(FinalClass.ts, 1, 8)) +>MyBaseClass : Symbol(MyBaseClass, Decl(FinalClass.ts, 0, 8)) + + extendedClassProperty: number; +>extendedClassProperty : Symbol(MyExtendedClass.extendedClassProperty, Decl(FinalClass.ts, 3, 67)) +} +=== tests/cases/compiler/Main.ts === +import { MyExtendedClass } from './FinalClass'; +>MyExtendedClass : Symbol(MyExtendedClass, Decl(Main.ts, 0, 8)) + +import { MyMixin } from './MixinClass'; +>MyMixin : Symbol(MyMixin, Decl(Main.ts, 1, 8)) + +const myExtendedClass = new MyExtendedClass('string'); +>myExtendedClass : Symbol(myExtendedClass, Decl(Main.ts, 3, 5)) +>MyExtendedClass : Symbol(MyExtendedClass, Decl(Main.ts, 0, 8)) + +const AnotherMixedClass = MyMixin(MyExtendedClass); +>AnotherMixedClass : Symbol(AnotherMixedClass, Decl(Main.ts, 5, 5)) +>MyMixin : Symbol(MyMixin, Decl(Main.ts, 1, 8)) +>MyExtendedClass : Symbol(MyExtendedClass, Decl(Main.ts, 0, 8)) + diff --git a/tests/baselines/reference/exportClassExtendingIntersection.types b/tests/baselines/reference/exportClassExtendingIntersection.types new file mode 100644 index 00000000000..5840c53a056 --- /dev/null +++ b/tests/baselines/reference/exportClassExtendingIntersection.types @@ -0,0 +1,84 @@ +=== tests/cases/compiler/BaseClass.ts === +export type Constructor = new (...args: any[]) => T; +>Constructor : Constructor +>T : T +>args : any[] +>T : T + +export class MyBaseClass { +>MyBaseClass : MyBaseClass +>T : T + + baseProperty: string; +>baseProperty : string + + constructor(value: T) {} +>value : T +>T : T +} +=== tests/cases/compiler/MixinClass.ts === +import { Constructor, MyBaseClass } from './BaseClass'; +>Constructor : any +>MyBaseClass : typeof MyBaseClass + +export interface MyMixin { +>MyMixin : MyMixin + + mixinProperty: string; +>mixinProperty : string +} + +export function MyMixin>>(base: T): T & Constructor { +>MyMixin : >>(base: T) => T & Constructor +>T : T +>Constructor : Constructor +>MyBaseClass : MyBaseClass +>base : T +>T : T +>T : T +>Constructor : Constructor +>MyMixin : MyMixin + + return class extends base { +>class extends base { mixinProperty: string; } : { new (...args: any[]): (Anonymous class); prototype: MyMixin.(Anonymous class); } & T +>base : MyBaseClass + + mixinProperty: string; +>mixinProperty : string + } +} +=== tests/cases/compiler/FinalClass.ts === +import { MyBaseClass } from './BaseClass'; +>MyBaseClass : typeof MyBaseClass + +import { MyMixin } from './MixinClass'; +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) + +export class MyExtendedClass extends MyMixin(MyBaseClass) { +>MyExtendedClass : MyExtendedClass +>MyMixin(MyBaseClass) : MyBaseClass & MyMixin +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) +>MyBaseClass : typeof MyBaseClass + + extendedClassProperty: number; +>extendedClassProperty : number +} +=== tests/cases/compiler/Main.ts === +import { MyExtendedClass } from './FinalClass'; +>MyExtendedClass : typeof MyExtendedClass + +import { MyMixin } from './MixinClass'; +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) + +const myExtendedClass = new MyExtendedClass('string'); +>myExtendedClass : MyExtendedClass +>new MyExtendedClass('string') : MyExtendedClass +>MyExtendedClass : typeof MyExtendedClass +>'string' : "string" + +const AnotherMixedClass = MyMixin(MyExtendedClass); +>AnotherMixedClass : typeof MyExtendedClass & (new (...args: any[]) => MyMixin) +>MyMixin(MyExtendedClass) : typeof MyExtendedClass & (new (...args: any[]) => MyMixin) +>MyMixin : MyBaseClass>(base: T) => T & (new (...args: any[]) => MyMixin) +>MyExtendedClass : typeof MyExtendedClass + diff --git a/tests/baselines/reference/mixinAccessModifiers.errors.txt b/tests/baselines/reference/mixinAccessModifiers.errors.txt index a93725e01d2..fa2fc4ac99a 100644 --- a/tests/baselines/reference/mixinAccessModifiers.errors.txt +++ b/tests/baselines/reference/mixinAccessModifiers.errors.txt @@ -5,25 +5,19 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(50,4): error TS2445: Pro tests/cases/conformance/classes/mixinAccessModifiers.ts(65,7): error TS2415: Class 'C1' incorrectly extends base class 'Private & Private2'. Type 'C1' is not assignable to type 'Private'. Property 'p' has conflicting declarations and is inaccessible in type 'C1'. -tests/cases/conformance/classes/mixinAccessModifiers.ts(65,7): error TS4093: 'extends' clause of exported class 'C1' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(66,7): error TS2415: Class 'C2' incorrectly extends base class 'Private & Protected'. Type 'C2' is not assignable to type 'Private'. Property 'p' has conflicting declarations and is inaccessible in type 'C2'. -tests/cases/conformance/classes/mixinAccessModifiers.ts(66,7): error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(67,7): error TS2415: Class 'C3' incorrectly extends base class 'Private & Public'. Type 'C3' is not assignable to type 'Private'. Property 'p' has conflicting declarations and is inaccessible in type 'C3'. -tests/cases/conformance/classes/mixinAccessModifiers.ts(67,7): error TS4093: 'extends' clause of exported class 'C3' refers to a type whose name cannot be referenced. -tests/cases/conformance/classes/mixinAccessModifiers.ts(69,7): error TS4093: 'extends' clause of exported class 'C4' refers to a type whose name cannot be referenced. -tests/cases/conformance/classes/mixinAccessModifiers.ts(82,7): error TS4093: 'extends' clause of exported class 'C5' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(84,6): error TS2445: Property 'p' is protected and only accessible within class 'C4' and its subclasses. tests/cases/conformance/classes/mixinAccessModifiers.ts(89,6): error TS2445: Property 's' is protected and only accessible within class 'typeof C4' and its subclasses. -tests/cases/conformance/classes/mixinAccessModifiers.ts(95,7): error TS4093: 'extends' clause of exported class 'C6' refers to a type whose name cannot be referenced. tests/cases/conformance/classes/mixinAccessModifiers.ts(97,6): error TS2445: Property 'p' is protected and only accessible within class 'C4' and its subclasses. tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Property 's' is protected and only accessible within class 'typeof C4' and its subclasses. -==== tests/cases/conformance/classes/mixinAccessModifiers.ts (17 errors) ==== +==== tests/cases/conformance/classes/mixinAccessModifiers.ts (11 errors) ==== type Constructable = new (...args: any[]) => object; class Private { @@ -101,26 +95,18 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Pr !!! error TS2415: Class 'C1' incorrectly extends base class 'Private & Private2'. !!! error TS2415: Type 'C1' is not assignable to type 'Private'. !!! error TS2415: Property 'p' has conflicting declarations and is inaccessible in type 'C1'. - ~~ -!!! error TS4093: 'extends' clause of exported class 'C1' refers to a type whose name cannot be referenced. class C2 extends Mix(Private, Protected) {} ~~ !!! error TS2415: Class 'C2' incorrectly extends base class 'Private & Protected'. !!! error TS2415: Type 'C2' is not assignable to type 'Private'. !!! error TS2415: Property 'p' has conflicting declarations and is inaccessible in type 'C2'. - ~~ -!!! error TS4093: 'extends' clause of exported class 'C2' refers to a type whose name cannot be referenced. class C3 extends Mix(Private, Public) {} ~~ !!! error TS2415: Class 'C3' incorrectly extends base class 'Private & Public'. !!! error TS2415: Type 'C3' is not assignable to type 'Private'. !!! error TS2415: Property 'p' has conflicting declarations and is inaccessible in type 'C3'. - ~~ -!!! error TS4093: 'extends' clause of exported class 'C3' refers to a type whose name cannot be referenced. class C4 extends Mix(Protected, Protected2) { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C4' refers to a type whose name cannot be referenced. f(c4: C4, c5: C5, c6: C6) { c4.p; c5.p; @@ -134,8 +120,6 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Pr } class C5 extends Mix(Protected, Public) { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C5' refers to a type whose name cannot be referenced. f(c4: C4, c5: C5, c6: C6) { c4.p; // Error, not in class deriving from Protected2 ~ @@ -153,8 +137,6 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Pr } class C6 extends Mix(Public, Public2) { - ~~ -!!! error TS4093: 'extends' clause of exported class 'C6' refers to a type whose name cannot be referenced. f(c4: C4, c5: C5, c6: C6) { c4.p; // Error, not in class deriving from Protected2 ~ diff --git a/tests/baselines/reference/mixinAccessModifiers.js b/tests/baselines/reference/mixinAccessModifiers.js index 8100c9db9e9..9abb2d00722 100644 --- a/tests/baselines/reference/mixinAccessModifiers.js +++ b/tests/baselines/reference/mixinAccessModifiers.js @@ -263,3 +263,66 @@ var C6 = (function (_super) { }; return C6; }(Mix(Public, Public2))); + + +//// [mixinAccessModifiers.d.ts] +declare type Constructable = new (...args: any[]) => object; +declare class Private { + constructor(...args: any[]); + private p; +} +declare class Private2 { + constructor(...args: any[]); + private p; +} +declare class Protected { + constructor(...args: any[]); + protected p: string; + protected static s: string; +} +declare class Protected2 { + constructor(...args: any[]); + protected p: string; + protected static s: string; +} +declare class Public { + constructor(...args: any[]); + p: string; + static s: string; +} +declare class Public2 { + constructor(...args: any[]); + p: string; + static s: string; +} +declare function f1(x: Private & Private2): void; +declare function f2(x: Private & Protected): void; +declare function f3(x: Private & Public): void; +declare function f4(x: Protected & Protected2): void; +declare function f5(x: Protected & Public): void; +declare function f6(x: Public & Public2): void; +declare function Mix(c1: T, c2: U): T & U; +declare var _C1_intersection_base: typeof Private & typeof Private2; +declare class C1 extends _C1_intersection_base { +} +declare var _C2_intersection_base: typeof Private & typeof Protected; +declare class C2 extends _C2_intersection_base { +} +declare var _C3_intersection_base: typeof Private & typeof Public; +declare class C3 extends _C3_intersection_base { +} +declare var _C4_intersection_base: typeof Protected & typeof Protected2; +declare class C4 extends _C4_intersection_base { + f(c4: C4, c5: C5, c6: C6): void; + static g(): void; +} +declare var _C5_intersection_base: typeof Protected & typeof Public; +declare class C5 extends _C5_intersection_base { + f(c4: C4, c5: C5, c6: C6): void; + static g(): void; +} +declare var _C6_intersection_base: typeof Public & typeof Public2; +declare class C6 extends _C6_intersection_base { + f(c4: C4, c5: C5, c6: C6): void; + static g(): void; +} From 241f54edc700735ff1759a1d0024d4b5a4f63c5b Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 2 May 2017 14:00:40 -0700 Subject: [PATCH 044/282] Don't allow to re-export a type when '--isolatedModules' is set --- src/compiler/checker.ts | 5 ++ src/compiler/diagnosticMessages.json | 4 ++ .../isolatedModulesReExportType.errors.txt | 38 +++++++++++++ .../reference/isolatedModulesReExportType.js | 57 +++++++++++++++++++ .../compiler/isolatedModulesReExportType.ts | 31 ++++++++++ 5 files changed, 135 insertions(+) create mode 100644 tests/baselines/reference/isolatedModulesReExportType.errors.txt create mode 100644 tests/baselines/reference/isolatedModulesReExportType.js create mode 100644 tests/cases/compiler/isolatedModulesReExportType.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 34a176ac23c..f55feaf87ed 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -21189,6 +21189,11 @@ namespace ts { Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === SyntaxKind.ExportSpecifier && compilerOptions.isolatedModules && !(target.flags & SymbolFlags.Value)) { + error(node, Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4d2997ba3a8..41936c0cc6a 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -635,6 +635,10 @@ "category": "Error", "code": 1203 }, + "Cannot re-export a type when the '--isolatedModules' flag is provided.": { + "category": "Error", + "code": 1205 + }, "Decorators are not valid here.": { "category": "Error", "code": 1206 diff --git a/tests/baselines/reference/isolatedModulesReExportType.errors.txt b/tests/baselines/reference/isolatedModulesReExportType.errors.txt new file mode 100644 index 00000000000..10c07cde084 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesReExportType.errors.txt @@ -0,0 +1,38 @@ +/user.ts(2,10): error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. +/user.ts(17,10): error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. + + +==== /user.ts (2 errors) ==== + // Error, can't re-export something that's only a type. + export { T } from "./exportT"; + ~ +!!! error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. + export import T2 = require("./exportEqualsT"); + + // OK, has a value side + export { C } from "./exportValue"; + + // OK, even though the namespace it exports is only types. + import * as NS from "./exportT"; + export { NS }; + + // OK, syntactically clear that a type is being re-exported. + export type T3 = T; + + // Error, not clear (to an isolated module) whether `T4` is a type. + import { T } from "./exportT"; + export { T as T4 }; + ~~~~~~~ +!!! error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided. + +==== /exportT.ts (0 errors) ==== + export type T = number; + +==== /exportValue.ts (0 errors) ==== + export class C {} + +==== /exportEqualsT.ts (0 errors) ==== + declare type T = number; + export = T; + + \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesReExportType.js b/tests/baselines/reference/isolatedModulesReExportType.js new file mode 100644 index 00000000000..545e5a81a8a --- /dev/null +++ b/tests/baselines/reference/isolatedModulesReExportType.js @@ -0,0 +1,57 @@ +//// [tests/cases/compiler/isolatedModulesReExportType.ts] //// + +//// [exportT.ts] +export type T = number; + +//// [exportValue.ts] +export class C {} + +//// [exportEqualsT.ts] +declare type T = number; +export = T; + + +//// [user.ts] +// Error, can't re-export something that's only a type. +export { T } from "./exportT"; +export import T2 = require("./exportEqualsT"); + +// OK, has a value side +export { C } from "./exportValue"; + +// OK, even though the namespace it exports is only types. +import * as NS from "./exportT"; +export { NS }; + +// OK, syntactically clear that a type is being re-exported. +export type T3 = T; + +// Error, not clear (to an isolated module) whether `T4` is a type. +import { T } from "./exportT"; +export { T as T4 }; + + +//// [exportT.js] +"use strict"; +exports.__esModule = true; +//// [exportEqualsT.js] +"use strict"; +exports.__esModule = true; +//// [exportValue.js] +"use strict"; +exports.__esModule = true; +var C = (function () { + function C() { + } + return C; +}()); +exports.C = C; +//// [user.js] +"use strict"; +exports.__esModule = true; +// OK, has a value side +var exportValue_1 = require("./exportValue"); +exports.C = exportValue_1.C; +// OK, even though the namespace it exports is only types. +var NS = require("./exportT"); +exports.NS = NS; diff --git a/tests/cases/compiler/isolatedModulesReExportType.ts b/tests/cases/compiler/isolatedModulesReExportType.ts new file mode 100644 index 00000000000..d1e05af6c83 --- /dev/null +++ b/tests/cases/compiler/isolatedModulesReExportType.ts @@ -0,0 +1,31 @@ +// @isolatedModules: true + +// @Filename: /exportT.ts +export type T = number; + +// @Filename: /exportValue.ts +export class C {} + +// @Filename: /exportEqualsT.ts +declare type T = number; +export = T; + + +// @Filename: /user.ts +// Error, can't re-export something that's only a type. +export { T } from "./exportT"; +export import T2 = require("./exportEqualsT"); + +// OK, has a value side +export { C } from "./exportValue"; + +// OK, even though the namespace it exports is only types. +import * as NS from "./exportT"; +export { NS }; + +// OK, syntactically clear that a type is being re-exported. +export type T3 = T; + +// Error, not clear (to an isolated module) whether `T4` is a type. +import { T } from "./exportT"; +export { T as T4 }; From e696bbcd22e590458866f5764968a5fc328a3f97 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 2 May 2017 14:11:46 -0700 Subject: [PATCH 045/282] Never elide an `export *` when `--isolatedModules` is set --- src/compiler/transformers/ts.ts | 2 +- .../isolatedModulesDontElideReExportStar.js | 12 ++++++++++++ .../isolatedModulesDontElideReExportStar.symbols | 8 ++++++++ .../isolatedModulesDontElideReExportStar.types | 8 ++++++++ .../compiler/isolatedModulesDontElideReExportStar.ts | 8 ++++++++ 5 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/isolatedModulesDontElideReExportStar.js create mode 100644 tests/baselines/reference/isolatedModulesDontElideReExportStar.symbols create mode 100644 tests/baselines/reference/isolatedModulesDontElideReExportStar.types create mode 100644 tests/cases/compiler/isolatedModulesDontElideReExportStar.ts diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 555855b5e23..4dca267955c 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -2922,7 +2922,7 @@ namespace ts { function visitExportDeclaration(node: ExportDeclaration): VisitResult { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { diff --git a/tests/baselines/reference/isolatedModulesDontElideReExportStar.js b/tests/baselines/reference/isolatedModulesDontElideReExportStar.js new file mode 100644 index 00000000000..4d546135f74 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDontElideReExportStar.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/isolatedModulesDontElideReExportStar.ts] //// + +//// [a.ts] +export type T = number; + +//// [b.ts] +export * from "./a"; + + +//// [a.js] +//// [b.js] +export * from "./a"; diff --git a/tests/baselines/reference/isolatedModulesDontElideReExportStar.symbols b/tests/baselines/reference/isolatedModulesDontElideReExportStar.symbols new file mode 100644 index 00000000000..38ab78bf498 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDontElideReExportStar.symbols @@ -0,0 +1,8 @@ +=== /a.ts === +export type T = number; +>T : Symbol(T, Decl(a.ts, 0, 0)) + +=== /b.ts === +export * from "./a"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesDontElideReExportStar.types b/tests/baselines/reference/isolatedModulesDontElideReExportStar.types new file mode 100644 index 00000000000..4f68c5ded89 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDontElideReExportStar.types @@ -0,0 +1,8 @@ +=== /a.ts === +export type T = number; +>T : number + +=== /b.ts === +export * from "./a"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/cases/compiler/isolatedModulesDontElideReExportStar.ts b/tests/cases/compiler/isolatedModulesDontElideReExportStar.ts new file mode 100644 index 00000000000..37a851a6292 --- /dev/null +++ b/tests/cases/compiler/isolatedModulesDontElideReExportStar.ts @@ -0,0 +1,8 @@ +// @isolatedModules: true +// @target: es6 + +// @filename: /a.ts +export type T = number; + +// @filename: /b.ts +export * from "./a"; From 729c1e19abb09fe4475313eb488c4c7e9dffc850 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 2 May 2017 15:00:56 -0700 Subject: [PATCH 046/282] __asyncDelegator cleanup --- src/compiler/transformers/esnext.ts | 6 +++--- .../emitter.asyncGenerators.classMethods.es2015.js | 12 ++++++------ .../emitter.asyncGenerators.classMethods.es5.js | 12 ++++++------ ...er.asyncGenerators.functionDeclarations.es2015.js | 12 ++++++------ ...itter.asyncGenerators.functionDeclarations.es5.js | 12 ++++++------ ...ter.asyncGenerators.functionExpressions.es2015.js | 12 ++++++------ ...mitter.asyncGenerators.functionExpressions.es5.js | 12 ++++++------ ...er.asyncGenerators.objectLiteralMethods.es2015.js | 12 ++++++------ ...itter.asyncGenerators.objectLiteralMethods.es5.js | 12 ++++++------ 9 files changed, 51 insertions(+), 51 deletions(-) diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 133272afc3a..8d88d9b286b 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -928,9 +928,9 @@ namespace ts { scoped: false, text: ` var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; ` }; diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js index 2a0ca50a97b..5f1b97b208c 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js @@ -127,9 +127,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -168,9 +168,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; class C5 { f() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js index a72f1dd27c5..4d78db84c03 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js @@ -263,9 +263,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -355,9 +355,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js index b25f69297d3..98e8291ac6a 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js @@ -90,9 +90,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -129,9 +129,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; function f5() { return __asyncGenerator(this, arguments, function* f5_1() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js index 87d5f1a2b01..c5b09b216d5 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js @@ -217,9 +217,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -304,9 +304,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js index 78909a55ab0..d491c0465f0 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js @@ -90,9 +90,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -129,9 +129,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; const f5 = function () { return __asyncGenerator(this, arguments, function* () { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js index 9f4811d8af9..7a40ba1808f 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js @@ -217,9 +217,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -304,9 +304,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js index 902197651be..22ffff01eec 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js @@ -110,9 +110,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -151,9 +151,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; const o5 = { f() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js index 34d970afdbe..a76028b028e 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js @@ -237,9 +237,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -326,9 +326,9 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, p; - return i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { return o[n] && function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + var i, p; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; From e12b708221ab7abe22e841d6b77a51d3d238c993 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 2 May 2017 15:33:13 -0700 Subject: [PATCH 047/282] For completions of union type, get all possible properties --- src/compiler/checker.ts | 19 ++++++++++++++++- src/compiler/types.ts | 5 +++++ src/services/completions.ts | 21 +++++++------------ .../cases/fourslash/completionListOfUnion.ts | 18 ++++++++++++++++ 4 files changed, 49 insertions(+), 14 deletions(-) create mode 100644 tests/cases/fourslash/completionListOfUnion.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ca5d65068a0..3c45942fd62 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -204,7 +204,8 @@ namespace ts { // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType + getApparentType, + getAllPossiblePropertiesOfType, }; const tupleTypes: GenericType[] = []; @@ -5648,6 +5649,22 @@ namespace ts { getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type: Type): Symbol[] { + if (type.flags & TypeFlags.Union) { + const props = createMap(); + for (const memberType of (type as UnionType).types) { + for (const { name } of getPropertiesOfType(memberType)) { + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type as UnionType, name)); + } + } + } + return arrayFrom(props.values()); + } else { + return getPropertiesOfType(type); + } + } + function getConstraintOfType(type: TypeVariable | UnionOrIntersectionType): Type { return type.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(type) : type.flags & TypeFlags.IndexedAccess ? getConstraintOfIndexedAccess(type) : diff --git a/src/compiler/types.ts b/src/compiler/types.ts index d9b4ca192f4..aad4f2680e3 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2564,6 +2564,11 @@ namespace ts { /* @internal */ getIdentifierCount(): number; /* @internal */ getSymbolCount(): number; /* @internal */ getTypeCount(): number; + + /** For a union, will include a property if it's defined in *any* of the member types. + * So for `{ a } | { b }`, this will include both `a` and `b`. + */ + /* @internal */ getAllPossiblePropertiesOfType(type: Type): Symbol[]; } export enum NodeBuilderFlags { diff --git a/src/services/completions.ts b/src/services/completions.ts index 6ac3762b4c7..f429ed34b6b 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -813,19 +813,16 @@ namespace ts.Completions { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - let typeForObject: Type; + let typeMembers: Symbol[]; let existingMembers: Declaration[]; if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); - + const typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = (objectLikeContainer).properties; } else if (objectLikeContainer.kind === SyntaxKind.ObjectBindingPattern) { @@ -849,7 +846,10 @@ namespace ts.Completions { } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = (objectLikeContainer).elements; } } @@ -861,11 +861,6 @@ namespace ts.Completions { Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - - const typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); diff --git a/tests/cases/fourslash/completionListOfUnion.ts b/tests/cases/fourslash/completionListOfUnion.ts new file mode 100644 index 00000000000..6026615f8c1 --- /dev/null +++ b/tests/cases/fourslash/completionListOfUnion.ts @@ -0,0 +1,18 @@ +/// + +// @strictNullChecks: true + +// Non-objects should be skipped, so `| number | null` should have no effect on completions. +////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null = { /*x*/ }; + +////interface I { a: number; } +////function f(...args: Array) {} +////f({ /*f*/ }); + +goTo.marker("x"); +verify.completionListContains("a", "(property) a: string | number"); +verify.completionListContains("b", "(property) b: number | boolean"); +verify.completionListContains("c", "(property) c: string"); + +goTo.marker("f"); +verify.completionListContains("a", "(property) a: number"); From f20a3306777e83ff2ca6ef3baecb4cbed05b0456 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 2 May 2017 16:19:26 -0700 Subject: [PATCH 048/282] add tests --- .../importNameCodeFixNewImportFromAtTypes.ts | 13 +++++++++++++ ...tNameCodeFixNewImportFromAtTypesScopedPackage.ts | 13 +++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 tests/cases/fourslash/importNameCodeFixNewImportFromAtTypes.ts create mode 100644 tests/cases/fourslash/importNameCodeFixNewImportFromAtTypesScopedPackage.ts diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypes.ts b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypes.ts new file mode 100644 index 00000000000..bca8f716200 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypes.ts @@ -0,0 +1,13 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: node_modules/@types/myLib/index.d.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([ +`import { f1 } from "myLib"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypesScopedPackage.ts b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypesScopedPackage.ts new file mode 100644 index 00000000000..3cf6cf8a32e --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFromAtTypesScopedPackage.ts @@ -0,0 +1,13 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: node_modules/@types/myLib__scoped/index.d.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([ +`import { f1 } from "@myLib/scoped"; + +f1();` +]); \ No newline at end of file From 5444f3cbd4c33c3c67823c7f8f5f2d3050a90768 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 2 May 2017 17:19:14 -0700 Subject: [PATCH 049/282] handle @types and scoped @types --- src/services/codefixes/importFixes.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 78c27a1276b..287e504e49f 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -500,6 +500,15 @@ namespace ts.codefix { } relativeFileName = removeFileExtension(relativeFileName); + + if (startsWith(relativeFileName, "@types/")) { + relativeFileName = relativeFileName.substr(/*"@types".length*/ 7); + if (relativeFileName.indexOf("__") !== -1) { + // Double underscores are used in DefinitelyTyped to delimit scoped packages. + relativeFileName = "@" + relativeFileName.replace("__", "/"); + } + } + if (endsWith(relativeFileName, "/index")) { relativeFileName = getDirectoryPath(relativeFileName); } From ac7429535ee37934d722d91dff989eba4a52f600 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 3 May 2017 08:05:40 -0700 Subject: [PATCH 050/282] Mark type arguments as used even if used in an invalid way --- src/compiler/checker.ts | 36 ++++-- ...ressionWithMissingTypeArgument1.errors.txt | 10 +- .../reference/functionCalls.errors.txt | 5 +- .../reference/parserAmbiguity1.errors.txt | 10 +- ...serAmbiguityWithBinaryOperator4.errors.txt | 8 +- .../parserGenericConstraint4.errors.txt | 5 +- .../parserGenericConstraint5.errors.txt | 5 +- .../parserGenericConstraint6.errors.txt | 5 +- .../parserGenericConstraint7.errors.txt | 5 +- .../parserGenericsInTypeContexts1.errors.txt | 26 +++- .../parserGenericsInTypeContexts2.errors.txt | 122 +++++++++++++++++- ...rGenericsInVariableDeclaration1.errors.txt | 40 +++++- .../parserMemberAccessExpression1.errors.txt | 17 ++- .../parserMissingLambdaOpenBrace1.errors.txt | 8 +- .../parserSkippedTokens20.errors.txt | 5 +- .../parserSuperExpression2.errors.txt | 5 +- .../parserSuperExpression3.errors.txt | 5 +- .../unusedInvalidTypeArguments.errors.txt | 78 +++++++++++ .../reference/unusedInvalidTypeArguments.js | 122 ++++++++++++++++++ .../compiler/unusedInvalidTypeArguments.ts | 46 +++++++ 20 files changed, 534 insertions(+), 29 deletions(-) create mode 100644 tests/baselines/reference/unusedInvalidTypeArguments.errors.txt create mode 100644 tests/baselines/reference/unusedInvalidTypeArguments.js create mode 100644 tests/cases/compiler/unusedInvalidTypeArguments.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ca5d65068a0..b6ff059380e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4714,7 +4714,7 @@ namespace ts { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgumentsFromTypeReferenceNode(baseTypeNode)); } else if (baseConstructorType.flags & TypeFlags.Any) { baseType = baseConstructorType; @@ -5238,7 +5238,7 @@ namespace ts { } const baseTypeNode = getBaseTypeNodeOfClass(classType); const isJavaScript = isInJavaScriptFile(baseTypeNode); - const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); + const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); const typeArgCount = length(typeArguments); const result: Signature[] = []; for (const baseSig of baseSignatures) { @@ -6501,7 +6501,7 @@ namespace ts { } // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { + function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol, typeArgs: Type[]): Type { const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); const typeParameters = type.localTypeParameters; if (typeParameters) { @@ -6520,7 +6520,7 @@ namespace ts { // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -6545,7 +6545,7 @@ namespace ts { // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { + function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol, typeArguments: Type[]): Type { const type = getDeclaredTypeOfSymbol(symbol); const typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -6561,7 +6561,6 @@ namespace ts { typeParameters.length); return unknownType; } - const typeArguments = map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -6609,16 +6608,18 @@ namespace ts { } function getTypeReferenceType(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol) { + const typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & SymbolFlags.TypeAlias) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & SymbolFlags.Value && node.kind === SyntaxKind.JSDocTypeReference) { @@ -6686,9 +6687,10 @@ namespace ts { ? (node).expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; + const typeArguments = typeArgumentsFromTypeReferenceNode(node); type = symbol === unknownSymbol ? unknownType : - symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol) : + symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol, typeArguments) : + symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol, typeArguments) : getTypeFromNonGenericTypeReference(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the @@ -6699,6 +6701,10 @@ namespace ts { return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): Type[] { + return map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node: TypeQueryNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { @@ -14303,7 +14309,17 @@ namespace ts { return true; } + function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression { + return node.kind === SyntaxKind.CallExpression || node.kind === SyntaxKind.NewExpression; + } + function resolveUntypedCall(node: CallLikeExpression): Signature { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === SyntaxKind.TaggedTemplateExpression) { checkExpression((node).template); } diff --git a/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt b/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt index aef540d958a..9ac8c650e00 100644 --- a/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt +++ b/tests/baselines/reference/callExpressionWithMissingTypeArgument1.errors.txt @@ -1,10 +1,16 @@ tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,1): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,5): error TS2304: Cannot find name 'a'. tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,7): error TS1110: Type expected. +tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,8): error TS2304: Cannot find name 'b'. -==== tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts (2 errors) ==== +==== tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts (4 errors) ==== Foo(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'a'. ~ -!!! error TS1110: Type expected. \ No newline at end of file +!!! error TS1110: Type expected. + ~ +!!! error TS2304: Cannot find name 'b'. \ No newline at end of file diff --git a/tests/baselines/reference/functionCalls.errors.txt b/tests/baselines/reference/functionCalls.errors.txt index 85e75876779..8e84aa81e0e 100644 --- a/tests/baselines/reference/functionCalls.errors.txt +++ b/tests/baselines/reference/functionCalls.errors.txt @@ -1,6 +1,7 @@ tests/cases/conformance/expressions/functionCalls/functionCalls.ts(8,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(9,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(10,1): error TS2347: Untyped function calls may not accept type arguments. +tests/cases/conformance/expressions/functionCalls/functionCalls.ts(10,8): error TS2304: Cannot find name 'Window'. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(25,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(26,1): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/expressions/functionCalls/functionCalls.ts(27,1): error TS2347: Untyped function calls may not accept type arguments. @@ -9,7 +10,7 @@ tests/cases/conformance/expressions/functionCalls/functionCalls.ts(33,1): error tests/cases/conformance/expressions/functionCalls/functionCalls.ts(34,1): error TS2347: Untyped function calls may not accept type arguments. -==== tests/cases/conformance/expressions/functionCalls/functionCalls.ts (9 errors) ==== +==== tests/cases/conformance/expressions/functionCalls/functionCalls.ts (10 errors) ==== // Invoke function call on value of type 'any' with no type arguments var anyVar: any; anyVar(0); @@ -26,6 +27,8 @@ tests/cases/conformance/expressions/functionCalls/functionCalls.ts(34,1): error anyVar(undefined); ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2347: Untyped function calls may not accept type arguments. + ~~~~~~ +!!! error TS2304: Cannot find name 'Window'. // Invoke function call on value of a subtype of Function with no call signatures with no type arguments diff --git a/tests/baselines/reference/parserAmbiguity1.errors.txt b/tests/baselines/reference/parserAmbiguity1.errors.txt index 00126360794..a5360161147 100644 --- a/tests/baselines/reference/parserAmbiguity1.errors.txt +++ b/tests/baselines/reference/parserAmbiguity1.errors.txt @@ -1,10 +1,16 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,1): error TS2304: Cannot find name 'f'. tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,3): error TS2304: Cannot find name 'g'. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,5): error TS2304: Cannot find name 'A'. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts(1,8): error TS2304: Cannot find name 'B'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguity1.ts (4 errors) ==== f(g(7)); ~ !!! error TS2304: Cannot find name 'f'. ~ -!!! error TS2304: Cannot find name 'g'. \ No newline at end of file +!!! error TS2304: Cannot find name 'g'. + ~ +!!! error TS2304: Cannot find name 'A'. + ~ +!!! error TS2304: Cannot find name 'B'. \ No newline at end of file diff --git a/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt b/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt index 2c7bef61598..41147305ce0 100644 --- a/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt +++ b/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt @@ -1,10 +1,16 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,9): error TS2347: Untyped function calls may not accept type arguments. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,11): error TS2304: Cannot find name 'b'. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,14): error TS2304: Cannot find name 'b'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts (3 errors) ==== function g() { var a, b, c; if (a(c + 1)) { } ~~~~~~~~~~~~~~ !!! error TS2347: Untyped function calls may not accept type arguments. + ~ +!!! error TS2304: Cannot find name 'b'. + ~ +!!! error TS2304: Cannot find name 'b'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericConstraint4.errors.txt b/tests/baselines/reference/parserGenericConstraint4.errors.txt index b42570593f7..f829bad913f 100644 --- a/tests/baselines/reference/parserGenericConstraint4.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint4.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint4.ts (2 errors) ==== class C > > { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericConstraint5.errors.txt b/tests/baselines/reference/parserGenericConstraint5.errors.txt index 3479731ae13..a20e617f5e6 100644 --- a/tests/baselines/reference/parserGenericConstraint5.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint5.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint5.ts (2 errors) ==== class C> > { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericConstraint6.errors.txt b/tests/baselines/reference/parserGenericConstraint6.errors.txt index 5efbcc8e8d0..be90daff826 100644 --- a/tests/baselines/reference/parserGenericConstraint6.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint6.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint6.ts (2 errors) ==== class C >> { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericConstraint7.errors.txt b/tests/baselines/reference/parserGenericConstraint7.errors.txt index ffff8ea2583..99054892fc0 100644 --- a/tests/baselines/reference/parserGenericConstraint7.errors.txt +++ b/tests/baselines/reference/parserGenericConstraint7.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts(1,19): error TS2304: Cannot find name 'List'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts(1,24): error TS2304: Cannot find name 'List'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericConstraint7.ts (2 errors) ==== class C>> { ~~~~ +!!! error TS2304: Cannot find name 'List'. + ~~~~ !!! error TS2304: Cannot find name 'List'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt index 477cc3edcdc..e98b618d78c 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt @@ -1,47 +1,71 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,17): error TS2304: Cannot find name 'A'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,33): error TS2304: Cannot find name 'B'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,35): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(4,9): error TS2315: Type 'C' is not generic. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(4,11): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(5,9): error TS2304: Cannot find name 'D'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(5,11): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(6,9): error TS2503: Cannot find namespace 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(6,13): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(7,9): error TS2503: Cannot find namespace 'G'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(7,15): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(8,9): error TS2304: Cannot find name 'K'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(8,11): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(11,16): error TS2304: Cannot find name 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(11,18): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(14,16): error TS2304: Cannot find name 'F'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(14,18): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts (9 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts (17 errors) ==== class C extends A implements B { ~ !!! error TS2304: Cannot find name 'A'. ~ !!! error TS2304: Cannot find name 'B'. + ~ +!!! error TS2304: Cannot find name 'T'. } var v1: C; ~~~~ !!! error TS2315: Type 'C' is not generic. + ~ +!!! error TS2304: Cannot find name 'T'. var v2: D = null; ~ !!! error TS2304: Cannot find name 'D'. + ~ +!!! error TS2304: Cannot find name 'T'. var v3: E.F; ~ !!! error TS2503: Cannot find namespace 'E'. + ~ +!!! error TS2304: Cannot find name 'T'. var v3: G.H.I; ~ !!! error TS2503: Cannot find namespace 'G'. + ~ +!!! error TS2304: Cannot find name 'T'. var v6: K[]; ~ !!! error TS2304: Cannot find name 'K'. + ~ +!!! error TS2304: Cannot find name 'T'. function f1(a: E) { ~ !!! error TS2304: Cannot find name 'E'. + ~ +!!! error TS2304: Cannot find name 'T'. } function f2(): F { ~ !!! error TS2304: Cannot find name 'F'. + ~ +!!! error TS2304: Cannot find name 'T'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt index f686b56bf89..79acb0fb6fd 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt @@ -1,47 +1,167 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,17): error TS2304: Cannot find name 'A'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,45): error TS2304: Cannot find name 'B'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,47): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,49): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,53): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,55): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,57): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,9): error TS2315: Type 'C' is not generic. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,11): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,13): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,17): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,19): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,21): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,9): error TS2304: Cannot find name 'D'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,11): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,13): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,17): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,19): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,21): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,9): error TS2503: Cannot find namespace 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,13): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,15): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,19): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,21): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,23): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,9): error TS2503: Cannot find namespace 'G'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,15): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,17): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,21): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,23): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,25): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,9): error TS2304: Cannot find name 'K'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,11): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,13): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,17): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,19): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,21): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,16): error TS2304: Cannot find name 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,18): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,20): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,24): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,26): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,28): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,16): error TS2304: Cannot find name 'F'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,18): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,20): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,24): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,26): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,28): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts (9 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts (49 errors) ==== class C extends A, Y>> implements B, Y>> { ~ !!! error TS2304: Cannot find name 'A'. ~ !!! error TS2304: Cannot find name 'B'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. } var v1: C, Y>>; ~~~~~~~~~~~~~~~~ !!! error TS2315: Type 'C' is not generic. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v2: D, Y>> = null; ~ !!! error TS2304: Cannot find name 'D'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v3: E.F, Y>>; ~ !!! error TS2503: Cannot find namespace 'E'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v4: G.H.I, Y>>; ~ !!! error TS2503: Cannot find namespace 'G'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. var v6: K, Y>>[]; ~ !!! error TS2304: Cannot find name 'K'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. function f1(a: E, Y>>) { ~ !!! error TS2304: Cannot find name 'E'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. } function f2(): F, Y>> { ~ !!! error TS2304: Cannot find name 'F'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt b/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt index 42f013cb250..6345f1ce34e 100644 --- a/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt +++ b/tests/baselines/reference/parserGenericsInVariableDeclaration1.errors.txt @@ -1,29 +1,65 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(1,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(1,13): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(2,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(2,13): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(4,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(4,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(4,17): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(5,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(5,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(5,17): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,17): error TS2304: Cannot find name 'Quux'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(7,22): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,9): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,13): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,17): error TS2304: Cannot find name 'Quux'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts(8,22): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts (6 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInVariableDeclaration1.ts (18 errors) ==== var v : Foo = 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo= 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo> = 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo>= 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo>> = 1; ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~~~~ +!!! error TS2304: Cannot find name 'Quux'. + ~ +!!! error TS2304: Cannot find name 'T'. var v : Foo>>= 1; ~~~ -!!! error TS2304: Cannot find name 'Foo'. \ No newline at end of file +!!! error TS2304: Cannot find name 'Foo'. + ~~~ +!!! error TS2304: Cannot find name 'Bar'. + ~~~~ +!!! error TS2304: Cannot find name 'Quux'. + ~ +!!! error TS2304: Cannot find name 'T'. \ No newline at end of file diff --git a/tests/baselines/reference/parserMemberAccessExpression1.errors.txt b/tests/baselines/reference/parserMemberAccessExpression1.errors.txt index 2006f5ac6d6..4e3e41770fe 100644 --- a/tests/baselines/reference/parserMemberAccessExpression1.errors.txt +++ b/tests/baselines/reference/parserMemberAccessExpression1.errors.txt @@ -1,25 +1,36 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(1,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(1,5): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(2,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(2,9): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,5): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,7): error TS1005: '(' expected. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,8): error TS2304: Cannot find name 'Bar'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(3,13): error TS1005: ')' expected. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,1): error TS2304: Cannot find name 'Foo'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,5): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,7): error TS1005: '(' expected. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,8): error TS2304: Cannot find name 'Bar'. +tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,12): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts(4,16): error TS1005: ')' expected. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts (10 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression1.ts (15 errors) ==== Foo(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. Foo.Bar(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. Foo.Bar(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS1005: '(' expected. ~~~ @@ -29,10 +40,14 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserMemberAccessExpression Foo.Bar(); ~~~ !!! error TS2304: Cannot find name 'Foo'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS1005: '(' expected. ~~~ !!! error TS2304: Cannot find name 'Bar'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS1005: ')' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt b/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt index d39986c9c01..728295b76cb 100644 --- a/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt +++ b/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt @@ -1,17 +1,23 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,19): error TS2304: Cannot find name 'Iterator'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,28): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,42): error TS2304: Cannot find name 'Query'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,48): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(3,16): error TS2304: Cannot find name 'fromDoWhile'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(4,13): error TS1005: '{' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(5,25): error TS2339: Property 'doWhile' does not exist on type 'C'. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts (5 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts (7 errors) ==== class C { where(filter: Iterator): Query { ~~~~~~~~ !!! error TS2304: Cannot find name 'Iterator'. + ~ +!!! error TS2304: Cannot find name 'T'. ~~~~~ !!! error TS2304: Cannot find name 'Query'. + ~ +!!! error TS2304: Cannot find name 'T'. return fromDoWhile(test => ~~~~~~~~~~~ !!! error TS2304: Cannot find name 'fromDoWhile'. diff --git a/tests/baselines/reference/parserSkippedTokens20.errors.txt b/tests/baselines/reference/parserSkippedTokens20.errors.txt index 774443d4d9a..d32f25a26b3 100644 --- a/tests/baselines/reference/parserSkippedTokens20.errors.txt +++ b/tests/baselines/reference/parserSkippedTokens20.errors.txt @@ -1,10 +1,13 @@ tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts(1,8): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts(1,10): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts(1,12): error TS1127: Invalid character. -==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens20.ts (3 errors) ==== var v: X(0); @@ -10,5 +11,7 @@ tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpressio !!! error TS2335: 'super' can only be referenced in a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. + ~ +!!! error TS2304: Cannot find name 'T'. } } \ No newline at end of file diff --git a/tests/baselines/reference/parserSuperExpression3.errors.txt b/tests/baselines/reference/parserSuperExpression3.errors.txt index 2fd81b29957..13faa304097 100644 --- a/tests/baselines/reference/parserSuperExpression3.errors.txt +++ b/tests/baselines/reference/parserSuperExpression3.errors.txt @@ -1,11 +1,14 @@ tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts(3,10): error TS2339: Property 'super' does not exist on type 'C'. +tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts(3,16): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts (1 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/SuperExpressions/parserSuperExpression3.ts (2 errors) ==== class C { M() { this.super(0); ~~~~~ !!! error TS2339: Property 'super' does not exist on type 'C'. + ~ +!!! error TS2304: Cannot find name 'T'. } } \ No newline at end of file diff --git a/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt b/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt new file mode 100644 index 00000000000..bd78839ab21 --- /dev/null +++ b/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt @@ -0,0 +1,78 @@ +/call.ts(1,21): error TS2307: Cannot find module 'unknown'. +/callAny.ts(3,1): error TS2347: Untyped function calls may not accept type arguments. +/callAny.ts(4,1): error TS2347: Untyped function calls may not accept type arguments. +/callAny.ts(4,3): error TS2304: Cannot find name 'InvalidReference'. +/classReference.ts(4,24): error TS2315: Type 'C' is not generic. +/interface.ts(1,21): error TS2307: Cannot find module 'unknown'. +/new.ts(1,21): error TS2307: Cannot find module 'unkown'. +/super.ts(1,19): error TS2307: Cannot find module 'unknown'. +/super.ts(8,17): error TS2304: Cannot find name 'InvalidReference'. +/typeReference.ts(6,17): error TS2315: Type 'U' is not generic. + + +==== /typeReference.ts (1 errors) ==== + // Tests that types are marked as used, even if used in places that don't accept type arguments. + + + type N = number; + type U = number; + export type Z = U; + ~~~~ +!!! error TS2315: Type 'U' is not generic. + +==== /classReference.ts (1 errors) ==== + type N = number; + class C { } + // This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. + export class D extends C {} + ~~~~ +!!! error TS2315: Type 'C' is not generic. + +==== /interface.ts (1 errors) ==== + import { Foo } from "unknown"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'unknown'. + export interface I { x: Foo; } + +==== /call.ts (1 errors) ==== + import { foo } from "unknown"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'unknown'. + type T = number; + foo(); + +==== /new.ts (1 errors) ==== + import { Foo } from "unkown"; + ~~~~~~~~ +!!! error TS2307: Cannot find module 'unkown'. + type T = number; + new Foo(); + +==== /callAny.ts (3 errors) ==== + declare var g: any; + type U = number; + g(); + ~~~~~~ +!!! error TS2347: Untyped function calls may not accept type arguments. + g(); // Should get error for type argument + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2347: Untyped function calls may not accept type arguments. + ~~~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'InvalidReference'. + +==== /super.ts (2 errors) ==== + import { C } from "unknown"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'unknown'. + + type T = number; + + export class D extends C { + m() { + super.m(1); + super.m(); // Should get error for type argument + ~~~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'InvalidReference'. + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/unusedInvalidTypeArguments.js b/tests/baselines/reference/unusedInvalidTypeArguments.js new file mode 100644 index 00000000000..955845ea01a --- /dev/null +++ b/tests/baselines/reference/unusedInvalidTypeArguments.js @@ -0,0 +1,122 @@ +//// [tests/cases/compiler/unusedInvalidTypeArguments.ts] //// + +//// [typeReference.ts] +// Tests that types are marked as used, even if used in places that don't accept type arguments. + + +type N = number; +type U = number; +export type Z = U; + +//// [classReference.ts] +type N = number; +class C { } +// This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. +export class D extends C {} + +//// [interface.ts] +import { Foo } from "unknown"; +export interface I { x: Foo; } + +//// [call.ts] +import { foo } from "unknown"; +type T = number; +foo(); + +//// [new.ts] +import { Foo } from "unkown"; +type T = number; +new Foo(); + +//// [callAny.ts] +declare var g: any; +type U = number; +g(); +g(); // Should get error for type argument + +//// [super.ts] +import { C } from "unknown"; + +type T = number; + +export class D extends C { + m() { + super.m(1); + super.m(); // Should get error for type argument + } +} + + +//// [typeReference.js] +"use strict"; +// Tests that types are marked as used, even if used in places that don't accept type arguments. +exports.__esModule = true; +//// [classReference.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var C = (function () { + function C() { + } + return C; +}()); +// This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. +var D = (function (_super) { + __extends(D, _super); + function D() { + return _super !== null && _super.apply(this, arguments) || this; + } + return D; +}(C)); +exports.D = D; +//// [interface.js] +"use strict"; +exports.__esModule = true; +//// [call.js] +"use strict"; +exports.__esModule = true; +var unknown_1 = require("unknown"); +unknown_1.foo(); +//// [new.js] +"use strict"; +exports.__esModule = true; +var unkown_1 = require("unkown"); +new unkown_1.Foo(); +//// [callAny.js] +g(); +g(); // Should get error for type argument +//// [super.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var unknown_1 = require("unknown"); +var D = (function (_super) { + __extends(D, _super); + function D() { + return _super !== null && _super.apply(this, arguments) || this; + } + D.prototype.m = function () { + _super.prototype.m.call(this, 1); + _super.prototype.m.call(this); // Should get error for type argument + }; + return D; +}(unknown_1.C)); +exports.D = D; diff --git a/tests/cases/compiler/unusedInvalidTypeArguments.ts b/tests/cases/compiler/unusedInvalidTypeArguments.ts new file mode 100644 index 00000000000..d0bcf0519a7 --- /dev/null +++ b/tests/cases/compiler/unusedInvalidTypeArguments.ts @@ -0,0 +1,46 @@ +// Tests that types are marked as used, even if used in places that don't accept type arguments. + +// @noUnusedLocals: true + +// @Filename: /typeReference.ts +type N = number; +type U = number; +export type Z = U; + +// @Filename: /classReference.ts +type N = number; +class C { } +// This uses getTypeFromClassOrInterfaceReference instead of getTypeFromTypeAliasReference. +export class D extends C {} + +// @Filename: /interface.ts +import { Foo } from "unknown"; +export interface I { x: Foo; } + +// @Filename: /call.ts +import { foo } from "unknown"; +type T = number; +foo(); + +// @Filename: /new.ts +import { Foo } from "unkown"; +type T = number; +new Foo(); + +// @Filename: /callAny.ts +declare var g: any; +type U = number; +g(); +g(); // Should get error for type argument + +// @Filename: /super.ts +import { C } from "unknown"; + +type T = number; + +export class D extends C { + m() { + super.m(1); + super.m(); // Should get error for type argument + } +} From ee1edf0421b2bda322ed7fc1ae3bfe07a110ed98 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 3 May 2017 09:42:19 -0700 Subject: [PATCH 051/282] Lower allowed levenshtein distance for suggestions And update baselines --- src/compiler/checker.ts | 18 +++++--- ...akInIterationOrSwitchStatement4.errors.txt | 4 +- ...torWithIncompleteTypeAnnotation.errors.txt | 16 +++---- .../continueInIterationStatement4.errors.txt | 4 +- .../reference/fixSignatureCaching.errors.txt | 12 ++--- .../letDeclarations-scopes2.errors.txt | 8 ++-- ...mUsingES6FeaturesWithOnlyES5Lib.errors.txt | 4 +- .../reference/parser10.1.1-8gs.errors.txt | 4 +- .../reference/parserRealSource11.errors.txt | 32 +++++++------- .../reference/parserRealSource7.errors.txt | 12 ++--- .../reference/parserRealSource8.errors.txt | 16 +++---- .../parserUnterminatedGeneric2.errors.txt | 4 +- ...akInIterationOrSwitchStatement4.errors.txt | 4 +- ...r_continueInIterationStatement4.errors.txt | 4 +- .../reference/parserharness.errors.txt | 16 +++---- .../reference/parserindenter.errors.txt | 12 ++--- .../reference/scanner10.1.1-8gs.errors.txt | 4 +- .../reference/scannertest1.errors.txt | 44 +++++++++---------- .../typeGuardFunctionErrors.errors.txt | 20 ++++----- .../reference/undeclaredMethod.errors.txt | 4 +- 20 files changed, 123 insertions(+), 119 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 76ff43f20e2..ca9ac8e09ea 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14197,13 +14197,15 @@ namespace ts { * except for candidates: * * With no name * * Whose meaning doesn't match the `meaning` parameter. - * * Whose length differs from the target name by more than 3. - * * Whose levenshtein distance is more than 0.7 of the length of the name - * (0.7 allows identifiers of length 3 to have a distance of 2 to allow for one substitution) + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. */ function getSpellingSuggestionForName(name: string, symbols: Symbol[], meaning: SymbolFlags): Symbol | undefined { - const worstDistance = name.length * 0.7; + const worstDistance = name.length * 0.4; + const maximumLengthDifference = Math.min(4, name.length * 0.34); let bestDistance = Number.MAX_VALUE; let bestCandidate = undefined; if (name.length > 30) { @@ -14211,16 +14213,18 @@ namespace ts { } name = name.toLowerCase(); for (const candidate of symbols) { - if (candidate.flags & meaning && candidate.name && Math.abs(candidate.name.length - name.length) < 4) { + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { const candidateName = candidate.name.toLowerCase(); if (candidateName === name) { return candidate; } - if (candidateName.length < 3) { + if (candidateName.length < 3 || name.length < 3) { continue; } const distance = levenshtein(candidateName, name); - if (distance < 2) { + if (distance < 3) { return candidate; } else if (distance < bestDistance && distance < worstDistance) { diff --git a/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt b/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt index 44e2d197f5a..c331ff09c2c 100644 --- a/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt +++ b/tests/baselines/reference/breakInIterationOrSwitchStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/breakInIterationOrSwitchStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? +tests/cases/compiler/breakInIterationOrSwitchStatement4.ts(1,15): error TS2304: Cannot find name 'something'. ==== tests/cases/compiler/breakInIterationOrSwitchStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? +!!! error TS2304: Cannot find name 'something'. break; } \ No newline at end of file diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 99d1e48bf28..1f561036035 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -64,12 +64,12 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,21): error T tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,44): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,69): error TS1110: Type expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,9): error TS1128: Declaration or statement expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2552: Cannot find name 'value'. Did you mean 'eval'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2304: Cannot find name 'Overloads'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2304: Cannot find name 'value'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,31): error TS1005: ',' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,9): error TS1128: Declaration or statement expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2304: Cannot find name 'Overloads'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,27): error TS1135: Argument expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,33): error TS1005: '(' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2552: Cannot find name 'string'. Did you mean 'String'? @@ -80,7 +80,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,65): error T tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,9): error TS2304: Cannot find name 'public'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS2304: Cannot find name 'DefaultValue'. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2552: Cannot find name 'value'. Did you mean 'eval'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2304: Cannot find name 'value'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,35): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2552: Cannot find name 'string'. Did you mean 'String'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,55): error TS1005: ';' expected. @@ -480,9 +480,9 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~~~~~~ -!!! error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? +!!! error TS2304: Cannot find name 'Overloads'. ~~~~~ -!!! error TS2552: Cannot find name 'value'. Did you mean 'eval'? +!!! error TS2304: Cannot find name 'value'. ~ !!! error TS1005: ',' expected. ~~~~~~ @@ -491,7 +491,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~~~~~~ -!!! error TS2552: Cannot find name 'Overloads'. Did you mean 'Overloading'? +!!! error TS2304: Cannot find name 'Overloads'. ~~~~~ !!! error TS1135: Argument expression expected. ~ @@ -515,7 +515,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DefaultValue'. ~~~~~ -!!! error TS2552: Cannot find name 'value'. Did you mean 'eval'? +!!! error TS2304: Cannot find name 'value'. ~ !!! error TS1109: Expression expected. ~~~~~~ diff --git a/tests/baselines/reference/continueInIterationStatement4.errors.txt b/tests/baselines/reference/continueInIterationStatement4.errors.txt index 24bed78aeca..bbc20570547 100644 --- a/tests/baselines/reference/continueInIterationStatement4.errors.txt +++ b/tests/baselines/reference/continueInIterationStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/continueInIterationStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? +tests/cases/compiler/continueInIterationStatement4.ts(1,15): error TS2304: Cannot find name 'something'. ==== tests/cases/compiler/continueInIterationStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? +!!! error TS2304: Cannot find name 'something'. continue; } \ No newline at end of file diff --git a/tests/baselines/reference/fixSignatureCaching.errors.txt b/tests/baselines/reference/fixSignatureCaching.errors.txt index 573857d6cb2..7a5c43c966e 100644 --- a/tests/baselines/reference/fixSignatureCaching.errors.txt +++ b/tests/baselines/reference/fixSignatureCaching.errors.txt @@ -64,9 +64,9 @@ tests/cases/conformance/fixSignatureCaching.ts(970,18): error TS2339: Property ' tests/cases/conformance/fixSignatureCaching.ts(975,16): error TS2304: Cannot find name 'module'. tests/cases/conformance/fixSignatureCaching.ts(975,42): error TS2304: Cannot find name 'module'. tests/cases/conformance/fixSignatureCaching.ts(976,37): error TS2304: Cannot find name 'module'. -tests/cases/conformance/fixSignatureCaching.ts(977,23): error TS2552: Cannot find name 'define'. Did you mean 'undefined'? -tests/cases/conformance/fixSignatureCaching.ts(977,48): error TS2552: Cannot find name 'define'. Did you mean 'undefined'? -tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2552: Cannot find name 'define'. Did you mean 'undefined'? +tests/cases/conformance/fixSignatureCaching.ts(977,23): error TS2304: Cannot find name 'define'. +tests/cases/conformance/fixSignatureCaching.ts(977,48): error TS2304: Cannot find name 'define'. +tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2304: Cannot find name 'define'. tests/cases/conformance/fixSignatureCaching.ts(979,23): error TS2304: Cannot find name 'window'. tests/cases/conformance/fixSignatureCaching.ts(980,37): error TS2304: Cannot find name 'window'. @@ -1182,12 +1182,12 @@ tests/cases/conformance/fixSignatureCaching.ts(980,37): error TS2304: Cannot fin !!! error TS2304: Cannot find name 'module'. } else if (typeof define === 'function' && define.amd) { ~~~~~~ -!!! error TS2552: Cannot find name 'define'. Did you mean 'undefined'? +!!! error TS2304: Cannot find name 'define'. ~~~~~~ -!!! error TS2552: Cannot find name 'define'. Did you mean 'undefined'? +!!! error TS2304: Cannot find name 'define'. return define; ~~~~~~ -!!! error TS2552: Cannot find name 'define'. Did you mean 'undefined'? +!!! error TS2304: Cannot find name 'define'. } else if (typeof window !== 'undefined') { ~~~~~~ !!! error TS2304: Cannot find name 'window'. diff --git a/tests/baselines/reference/letDeclarations-scopes2.errors.txt b/tests/baselines/reference/letDeclarations-scopes2.errors.txt index e451eb0ad07..5da8d99d397 100644 --- a/tests/baselines/reference/letDeclarations-scopes2.errors.txt +++ b/tests/baselines/reference/letDeclarations-scopes2.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/letDeclarations-scopes2.ts(8,5): error TS2552: Cannot find name 'local2'. Did you mean 'local'? tests/cases/compiler/letDeclarations-scopes2.ts(20,5): error TS2552: Cannot find name 'local2'. Did you mean 'local'? -tests/cases/compiler/letDeclarations-scopes2.ts(23,1): error TS2552: Cannot find name 'local'. Did you mean 'global'? -tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2552: Cannot find name 'local2'. Did you mean 'global'? +tests/cases/compiler/letDeclarations-scopes2.ts(23,1): error TS2304: Cannot find name 'local'. +tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2304: Cannot find name 'local2'. ==== tests/cases/compiler/letDeclarations-scopes2.ts (4 errors) ==== @@ -33,9 +33,9 @@ tests/cases/compiler/letDeclarations-scopes2.ts(25,1): error TS2552: Cannot find local; // Error ~~~~~ -!!! error TS2552: Cannot find name 'local'. Did you mean 'global'? +!!! error TS2304: Cannot find name 'local'. global; // OK local2; // Error ~~~~~~ -!!! error TS2552: Cannot find name 'local2'. Did you mean 'global'? +!!! error TS2304: Cannot find name 'local2'. \ No newline at end of file diff --git a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt index b56b03de533..9b5f0ada58f 100644 --- a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt +++ b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(4,18): error TS2339: Property 'from' does not exist on type 'ArrayConstructor'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(10,13): error TS2304: Cannot find name 'Map'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(17,5): error TS2339: Property 'name' does not exist on type '() => void'. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'asin'? tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(25,6): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(29,18): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(33,13): error TS2304: Cannot find name 'Proxy'. @@ -40,7 +40,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.t // Using ES6 math Math.sign(1); ~~~~ -!!! error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? +!!! error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'asin'? // Using ES6 object var o = { diff --git a/tests/baselines/reference/parser10.1.1-8gs.errors.txt b/tests/baselines/reference/parser10.1.1-8gs.errors.txt index 442b90fc85e..84e45644e94 100644 --- a/tests/baselines/reference/parser10.1.1-8gs.errors.txt +++ b/tests/baselines/reference/parser10.1.1-8gs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(16,7): error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? +tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(16,7): error TS2304: Cannot find name 'NotEarlyError'. tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(17,5): error TS1212: Identifier expected. 'public' is a reserved word in strict mode. @@ -20,7 +20,7 @@ tests/cases/conformance/parser/ecmascript5/parser10.1.1-8gs.ts(17,5): error TS12 "use strict"; throw NotEarlyError; ~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? +!!! error TS2304: Cannot find name 'NotEarlyError'. var public = 1; ~~~~~~ !!! error TS1212: Identifier expected. 'public' is a reserved word in strict mode. diff --git a/tests/baselines/reference/parserRealSource11.errors.txt b/tests/baselines/reference/parserRealSource11.errors.txt index 84264ee5512..ee15d465ea0 100644 --- a/tests/baselines/reference/parserRealSource11.errors.txt +++ b/tests/baselines/reference/parserRealSource11.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(13,22): error TS2304: Cannot find name 'Type'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(14,24): error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(14,24): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(17,38): error TS2304: Cannot find name 'CompilerDiagnostics'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(24,39): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(36,36): error TS2304: Cannot find name 'TypeFlow'. @@ -30,7 +30,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(103,22): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(108,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(119,31): error TS2304: Cannot find name 'PrintContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(130,17): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(130,37): error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(130,37): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(137,17): error TS2304: Cannot find name 'nodeTypeTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(138,24): error TS2304: Cannot find name 'nodeTypeTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(141,30): error TS2304: Cannot find name 'NodeType'. @@ -258,7 +258,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1024,47): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1032,36): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1033,29): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1034,28): error TS2304: Cannot find name 'BasicBlock'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1036,31): error TS2552: Cannot find name 'ControlFlowContext'. Did you mean 'controlFlowPrefix'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1036,31): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1038,69): error TS2304: Cannot find name 'IAstWalker'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1043,26): error TS2304: Cannot find name 'getAstWalkerFactory'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1050,36): error TS2304: Cannot find name 'TypeFlow'. @@ -343,7 +343,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1286,36): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1290,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1290,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1295,32): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1297,27): error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1297,27): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1306,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1314,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1317,30): error TS2304: Cannot find name 'Emitter'. @@ -474,8 +474,8 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2107,50): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2108,54): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2112,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2119,42): error TS2304: Cannot find name 'ControlFlowContext'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2120,36): error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2122,32): error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2120,36): error TS2304: Cannot find name 'BasicBlock'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2122,32): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2145,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2150,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2150,48): error TS2304: Cannot find name 'TokenID'. @@ -500,9 +500,9 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2231,48): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2237,48): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2240,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2245,42): error TS2304: Cannot find name 'ControlFlowContext'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2248,36): error TS2552: Cannot find name 'BasicBlock'. Did you mean 'bodBlock'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2248,36): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2259,36): error TS2304: Cannot find name 'TypeFlow'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2263,33): error TS2552: Cannot find name 'ValueLocation'. Did you mean 'LocationInfo'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2263,33): error TS2304: Cannot find name 'ValueLocation'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2264,30): error TS2304: Cannot find name 'VariableSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2269,38): error TS2304: Cannot find name 'TypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2300,19): error TS2304: Cannot find name 'NodeType'. @@ -537,7 +537,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'Type'. public flags = ASTFlags.Writeable; ~~~~~~~~ -!!! error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? +!!! error TS2304: Cannot find name 'ASTFlags'. // REVIEW: for diagnostic purposes public passCreated: number = CompilerDiagnostics.analysisPass; @@ -713,7 +713,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~ -!!! error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? +!!! error TS2304: Cannot find name 'ASTFlags'. lab += " (Error)"; } context.writeLine(lab); @@ -2075,7 +2075,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error var context = new ControlFlowContext(entry, exit); ~~~~~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ControlFlowContext'. Did you mean 'controlFlowPrefix'? +!!! error TS2304: Cannot find name 'ControlFlowContext'. var controlFlowPrefix = (ast: AST, parent: AST, walker: IAstWalker) => { ~~~~~~~~~~ @@ -2506,7 +2506,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error super(nodeType); this.flags |= ASTFlags.IsStatement; ~~~~~~~~ -!!! error TS2552: Cannot find name 'ASTFlags'. Did you mean 'ASTList'? +!!! error TS2304: Cannot find name 'ASTFlags'. } public isLoop() { return false; } @@ -3591,11 +3591,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'ControlFlowContext'. var afterFinally = new BasicBlock(); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? +!!! error TS2304: Cannot find name 'BasicBlock'. context.walk(this.tryNode, this); var finBlock = new BasicBlock(); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'BasicBlock'. Did you mean 'finBlock'? +!!! error TS2304: Cannot find name 'BasicBlock'. if (context.current) { context.current.addSuccessor(finBlock); } @@ -3771,7 +3771,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error context.addContent(this.param); var bodBlock = new BasicBlock(); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'BasicBlock'. Did you mean 'bodBlock'? +!!! error TS2304: Cannot find name 'BasicBlock'. context.current.addSuccessor(bodBlock); context.current = bodBlock; } @@ -3790,7 +3790,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error this.param = typeFlow.typeCheck(this.param); var exceptVar = new ValueLocation(); ~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ValueLocation'. Did you mean 'LocationInfo'? +!!! error TS2304: Cannot find name 'ValueLocation'. var varSym = new VariableSymbol((this.param).id.text, ~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'VariableSymbol'. diff --git a/tests/baselines/reference/parserRealSource7.errors.txt b/tests/baselines/reference/parserRealSource7.errors.txt index cbe09f8e708..67f3f5e9a28 100644 --- a/tests/baselines/reference/parserRealSource7.errors.txt +++ b/tests/baselines/reference/parserRealSource7.errors.txt @@ -53,11 +53,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(186,75): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(189,25): error TS2304: Cannot find name 'ModuleDeclaration'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(189,46): error TS2304: Cannot find name 'ModuleDeclaration'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(191,25): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(191,54): error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(191,54): error TS2304: Cannot find name 'ModuleFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(192,22): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(192,51): error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(192,51): error TS2304: Cannot find name 'ModuleFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(194,26): error TS2304: Cannot find name 'hasFlag'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(194,55): error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(194,55): error TS2304: Cannot find name 'ModuleFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(195,25): error TS2304: Cannot find name 'Identifier'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(197,25): error TS2304: Cannot find name 'isQuoted'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(200,25): error TS2304: Cannot find name 'TypeSymbol'. @@ -606,18 +606,18 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? +!!! error TS2304: Cannot find name 'ModuleFlags'. var isEnum = hasFlag(moduleDecl.modFlags, ModuleFlags.IsEnum); ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? +!!! error TS2304: Cannot find name 'ModuleFlags'. var isGlobal = context.scopeChain.container == context.checker.gloMod; var isExported = hasFlag(moduleDecl.modFlags, ModuleFlags.Exported); ~~~~~~~ !!! error TS2304: Cannot find name 'hasFlag'. ~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ModuleFlags'. Did you mean 'moduleDecl'? +!!! error TS2304: Cannot find name 'ModuleFlags'. var modName = (moduleDecl.name).text; ~~~~~~~~~~ !!! error TS2304: Cannot find name 'Identifier'. diff --git a/tests/baselines/reference/parserRealSource8.errors.txt b/tests/baselines/reference/parserRealSource8.errors.txt index d4d26e5489f..4fbf039ae0a 100644 --- a/tests/baselines/reference/parserRealSource8.errors.txt +++ b/tests/baselines/reference/parserRealSource8.errors.txt @@ -74,19 +74,19 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(284,38): error T tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(286,55): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(292,43): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(309,29): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,31): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,31): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,49): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(310,84): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(311,36): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,38): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,38): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,56): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(312,98): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(313,35): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,37): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,37): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,55): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(314,96): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(315,42): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,44): error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,44): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,62): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(316,110): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(321,26): error TS2304: Cannot find name 'SymbolScopeBuilder'. @@ -598,7 +598,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var funcMembers = new ScopedMembers(new DualStringHashTable(funcTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +!!! error TS2304: Cannot find name 'ScopedMembers'. ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ @@ -608,7 +608,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var ambientFuncMembers = new ScopedMembers(new DualStringHashTable(ambientFuncTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +!!! error TS2304: Cannot find name 'ScopedMembers'. ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ @@ -618,7 +618,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var funcStaticMembers = new ScopedMembers(new DualStringHashTable(funcStaticTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +!!! error TS2304: Cannot find name 'ScopedMembers'. ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ @@ -628,7 +628,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T !!! error TS2304: Cannot find name 'StringHashTable'. var ambientFuncStaticMembers = new ScopedMembers(new DualStringHashTable(ambientFuncStaticTable, new StringHashTable())); ~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ScopedMembers'. Did you mean 'funcMembers'? +!!! error TS2304: Cannot find name 'ScopedMembers'. ~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'DualStringHashTable'. ~~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt index dde7576bfc4..2b663a8cd4f 100644 --- a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt +++ b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt @@ -5,7 +5,7 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,16): error TS2304: Cannot find name 'context'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,23): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,25): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,30): error TS2552: Cannot find name 'value'. Did you mean 'eval'? +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,30): error TS2304: Cannot find name 'value'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,35): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,37): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,41): error TS1005: ';' expected. @@ -35,7 +35,7 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener ~~~ !!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? ~~~~~ -!!! error TS2552: Cannot find name 'value'. Did you mean 'eval'? +!!! error TS2304: Cannot find name 'value'. ~ !!! error TS1005: ',' expected. ~~~ diff --git a/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt b/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt index db5bd15b155..8d9acd6fb57 100644 --- a/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt +++ b/tests/baselines/reference/parser_breakInIterationOrSwitchStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Statements/BreakStatements/parser_breakInIterationOrSwitchStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? +tests/cases/conformance/parser/ecmascript5/Statements/BreakStatements/parser_breakInIterationOrSwitchStatement4.ts(1,15): error TS2304: Cannot find name 'something'. ==== tests/cases/conformance/parser/ecmascript5/Statements/BreakStatements/parser_breakInIterationOrSwitchStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? +!!! error TS2304: Cannot find name 'something'. break; } \ No newline at end of file diff --git a/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt b/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt index 4036de0d2a2..5d87d3e3c71 100644 --- a/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt +++ b/tests/baselines/reference/parser_continueInIterationStatement4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Statements/ContinueStatements/parser_continueInIterationStatement4.ts(1,15): error TS2552: Cannot find name 'something'. Did you mean 'String'? +tests/cases/conformance/parser/ecmascript5/Statements/ContinueStatements/parser_continueInIterationStatement4.ts(1,15): error TS2304: Cannot find name 'something'. ==== tests/cases/conformance/parser/ecmascript5/Statements/ContinueStatements/parser_continueInIterationStatement4.ts (1 errors) ==== for (var i in something) { ~~~~~~~~~ -!!! error TS2552: Cannot find name 'something'. Did you mean 'String'? +!!! error TS2304: Cannot find name 'something'. continue; } \ No newline at end of file diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index fc8d1c5a322..b9ac11d3b6c 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -25,11 +25,11 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,42): e tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(781,23): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(794,49): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(795,49): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,115): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(999,40): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1041,43): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1044,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? @@ -1153,16 +1153,16 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var script = compiler.scripts.members[m]; var enclosingScopeContext = TypeScript.findEnclosingScopeAt(new TypeScript.NullLogger(), script, new TypeScript.StringSourceText(code), 0, false); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? var entries = new TypeScript.ScopeTraversal(compiler).getScopeEntries(enclosingScopeContext); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'script2'? +!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? for (var i = 0; i < entries.length; i++) { if (entries[i].name === targetIdentifier) { diff --git a/tests/baselines/reference/parserindenter.errors.txt b/tests/baselines/reference/parserindenter.errors.txt index 997b56b7db9..5e97bfdabc1 100644 --- a/tests/baselines/reference/parserindenter.errors.txt +++ b/tests/baselines/reference/parserindenter.errors.txt @@ -57,7 +57,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(265,91): tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(266,34): error TS2304: Cannot find name 'IndentationInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(274,53): error TS2304: Cannot find name 'AuthorParseNodeKind'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(278,50): error TS2304: Cannot find name 'Span'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(279,28): error TS2552: Cannot find name 'ParseTree'. Did you mean 'parseInt'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(279,28): error TS2304: Cannot find name 'ParseTree'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(288,60): error TS2304: Cannot find name 'TokenSpan'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(288,77): error TS2304: Cannot find name 'ParseNode'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(288,89): error TS2304: Cannot find name 'IndentationInfo'. @@ -112,8 +112,8 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(634,21): tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(665,34): error TS2304: Cannot find name 'IndentationEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(686,45): error TS2304: Cannot find name 'TextEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(688,34): error TS2304: Cannot find name 'IndentationEditInfo'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(695,35): error TS2304: Cannot find name 'IndentationEditInfo'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(698,39): error TS2304: Cannot find name 'IndentationEditInfo'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(695,35): error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(698,39): error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(706,42): error TS2304: Cannot find name 'TextEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(709,50): error TS2304: Cannot find name 'TokenSpan'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(709,67): error TS2304: Cannot find name 'ParseNode'. @@ -527,7 +527,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): !!! error TS2304: Cannot find name 'Span'. node = ParseTree.FindCommonParentNode(semiColonStartSpan, semiColonStartSpan, node); ~~~~~~~~~ -!!! error TS2552: Cannot find name 'ParseTree'. Did you mean 'parseInt'? +!!! error TS2304: Cannot find name 'ParseTree'. indentationInfo = node.GetEffectiveChildrenIndentation(this); return indentationInfo; } @@ -1053,12 +1053,12 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): indentationInfo = IndentationEditInfo.create2(indent.Position, indent.ReplaceWith, lineStartPosition, lineIndentLength); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'IndentationEditInfo'. +!!! error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? } else { indentationInfo = new IndentationEditInfo(indent); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'IndentationEditInfo'. +!!! error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? } this.indentationBag.AddIndent(indentationInfo); diff --git a/tests/baselines/reference/scanner10.1.1-8gs.errors.txt b/tests/baselines/reference/scanner10.1.1-8gs.errors.txt index f8b0c121ee0..6e75f195c26 100644 --- a/tests/baselines/reference/scanner10.1.1-8gs.errors.txt +++ b/tests/baselines/reference/scanner10.1.1-8gs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(16,7): error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? +tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(16,7): error TS2304: Cannot find name 'NotEarlyError'. tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(17,1): error TS7027: Unreachable code detected. tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(17,5): error TS1212: Identifier expected. 'public' is a reserved word in strict mode. @@ -21,7 +21,7 @@ tests/cases/conformance/scanner/ecmascript5/scanner10.1.1-8gs.ts(17,5): error TS "use strict"; throw NotEarlyError; ~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'NotEarlyError'. Did you mean 'SyntaxError'? +!!! error TS2304: Cannot find name 'NotEarlyError'. var public = 1; ~~~ !!! error TS7027: Unreachable code detected. diff --git a/tests/baselines/reference/scannertest1.errors.txt b/tests/baselines/reference/scannertest1.errors.txt index 6a98346e001..fce2a0b292a 100644 --- a/tests/baselines/reference/scannertest1.errors.txt +++ b/tests/baselines/reference/scannertest1.errors.txt @@ -1,19 +1,19 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(1,1): error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,21): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,47): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,21): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,47): error TS2304: Cannot find name 'CharacterCodes'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(9,16): error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,22): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,47): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,22): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,47): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,22): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(10,47): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,22): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(11,47): error TS2304: Cannot find name 'CharacterCodes'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(15,9): error TS2304: Cannot find name 'Debug'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(15,22): error TS2662: Cannot find name 'isHexDigit'. Did you mean the static member 'CharacterInfo.isHexDigit'? tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(16,16): error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(17,20): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,21): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,46): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(19,23): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(17,20): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,21): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(18,46): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(19,23): error TS2304: Cannot find name 'CharacterCodes'. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2304: Cannot find name 'CharacterCodes'. ==== tests/cases/conformance/scanner/ecmascript5/scannertest1.ts (16 errors) ==== @@ -25,9 +25,9 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2552 public static isDecimalDigit(c: number): boolean { return c >= CharacterCodes._0 && c <= CharacterCodes._9; ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. } public static isHexDigit(c: number): boolean { @@ -36,14 +36,14 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2552 !!! error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? (c >= CharacterCodes.A && c <= CharacterCodes.F) || ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. (c >= CharacterCodes.a && c <= CharacterCodes.f); ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. } public static hexValue(c: number): number { @@ -57,18 +57,18 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2552 !!! error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? ? (c - CharacterCodes._0) ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. : (c >= CharacterCodes.A && c <= CharacterCodes.F) ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. ? c - CharacterCodes.A + 10 ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. : c - CharacterCodes.a + 10; ~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'CharacterCodes'. Did you mean 'CharacterInfo'? +!!! error TS2304: Cannot find name 'CharacterCodes'. } } diff --git a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt index 1c57ec5cf68..b9d884939bd 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt +++ b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt @@ -2,7 +2,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(1,7): tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(14,5): error TS2322: Type '""' is not assignable to type 'boolean'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,55): error TS2304: Cannot find name 'x'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,57): error TS1144: '{' or ';' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,57): error TS2552: Cannot find name 'is'. Did you mean 'isB'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,57): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,60): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,62): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(21,33): error TS2304: Cannot find name 'x'. @@ -34,16 +34,16 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(84,1): tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(90,1): error TS2322: Type '(p1: any, p2: any, p3: any) => p1 is A' is not assignable to type '(p1: any, p2: any) => p1 is A'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,9): error TS2304: Cannot find name 'b'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,11): error TS1005: '=' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,11): error TS2552: Cannot find name 'is'. Did you mean 'isB'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,11): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,14): error TS1005: ',' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,14): error TS2300: Duplicate identifier 'A'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,16): error TS2304: Cannot find name 'b'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,18): error TS1005: '=' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,18): error TS2552: Cannot find name 'is'. Did you mean 'isB'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,18): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,21): error TS1005: ',' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,20): error TS2304: Cannot find name 'b'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,22): error TS1144: '{' or ';' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,22): error TS2552: Cannot find name 'is'. Did you mean 'isB'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,22): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,25): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,27): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(103,25): error TS1228: A type predicate is only allowed in return type position for functions and methods. @@ -55,7 +55,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(110,9) tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(115,18): error TS1228: A type predicate is only allowed in return type position for functions and methods. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,22): error TS2304: Cannot find name 'p1'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,25): error TS1005: ';' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,25): error TS2552: Cannot find name 'is'. Did you mean 'isB'? +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,25): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(119,28): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(120,1): error TS1128: Declaration or statement expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(123,20): error TS1229: A type predicate cannot reference a rest parameter. @@ -91,7 +91,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1144: '{' or ';' expected. ~~ -!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? +!!! error TS2304: Cannot find name 'is'. ~ !!! error TS1005: ';' expected. ~ @@ -223,7 +223,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1005: '=' expected. ~~ -!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? +!!! error TS2304: Cannot find name 'is'. ~ !!! error TS1005: ',' expected. ~ @@ -234,7 +234,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1005: '=' expected. ~~ -!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? +!!! error TS2304: Cannot find name 'is'. ~ !!! error TS1005: ',' expected. function b3(): A | b is A { @@ -243,7 +243,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1144: '{' or ';' expected. ~~ -!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? +!!! error TS2304: Cannot find name 'is'. ~ !!! error TS1005: ';' expected. ~ @@ -289,7 +289,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(136,39 ~~ !!! error TS1005: ';' expected. ~~ -!!! error TS2552: Cannot find name 'is'. Did you mean 'isB'? +!!! error TS2304: Cannot find name 'is'. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/undeclaredMethod.errors.txt b/tests/baselines/reference/undeclaredMethod.errors.txt index 4e7bf187440..942d1908182 100644 --- a/tests/baselines/reference/undeclaredMethod.errors.txt +++ b/tests/baselines/reference/undeclaredMethod.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/undeclaredMethod.ts(10,3): error TS2551: Property 'saltbar' does not exist on type 'C'. Did you mean 'salt'? +tests/cases/compiler/undeclaredMethod.ts(10,3): error TS2339: Property 'saltbar' does not exist on type 'C'. ==== tests/cases/compiler/undeclaredMethod.ts (1 errors) ==== @@ -13,6 +13,6 @@ tests/cases/compiler/undeclaredMethod.ts(10,3): error TS2551: Property 'saltbar' c.salt(); // cool c.saltbar(); // crash ~~~~~~~ -!!! error TS2551: Property 'saltbar' does not exist on type 'C'. Did you mean 'salt'? +!!! error TS2339: Property 'saltbar' does not exist on type 'C'. \ No newline at end of file From c61a371e6239a96d8eb0d469b8ad157c9a341e93 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 3 May 2017 10:06:55 -0700 Subject: [PATCH 052/282] Make TokenRange an interface and remove `ITokenAccess` delegation --- src/services/formatting/tokenRange.ts | 139 ++++++++++---------------- 1 file changed, 54 insertions(+), 85 deletions(-) diff --git a/src/services/formatting/tokenRange.ts b/src/services/formatting/tokenRange.ts index 28f22cec475..29855279e25 100644 --- a/src/services/formatting/tokenRange.ts +++ b/src/services/formatting/tokenRange.ts @@ -3,23 +3,13 @@ /* @internal */ namespace ts.formatting { export namespace Shared { - export interface ITokenAccess { - GetTokens(): SyntaxKind[]; - Contains(token: SyntaxKind): boolean; - isSpecific(): boolean; + const allTokens: SyntaxKind[] = []; + for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) { + allTokens.push(token); } - export class TokenRangeAccess implements ITokenAccess { - private tokens: SyntaxKind[]; - - constructor(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[]) { - this.tokens = []; - for (let token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } + class TokenValuesAccess implements TokenRange { + constructor(private readonly tokens: SyntaxKind[] = []) { } public GetTokens(): SyntaxKind[] { return this.tokens; @@ -32,27 +22,8 @@ namespace ts.formatting { public isSpecific() { return true; } } - export class TokenValuesAccess implements ITokenAccess { - private tokens: SyntaxKind[]; - - constructor(tks: SyntaxKind[]) { - this.tokens = tks && tks.length ? tks : []; - } - - public GetTokens(): SyntaxKind[] { - return this.tokens; - } - - public Contains(token: SyntaxKind): boolean { - return this.tokens.indexOf(token) >= 0; - } - - public isSpecific() { return true; } - } - - export class TokenSingleValueAccess implements ITokenAccess { - constructor(public token: SyntaxKind) { - } + class TokenSingleValueAccess implements TokenRange { + constructor(private readonly token: SyntaxKind) {} public GetTokens(): SyntaxKind[] { return [this.token]; @@ -65,12 +36,7 @@ namespace ts.formatting { public isSpecific() { return true; } } - const allTokens: SyntaxKind[] = []; - for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) { - allTokens.push(token); - } - - export class TokenAllAccess implements ITokenAccess { + class TokenAllAccess implements TokenRange { public GetTokens(): SyntaxKind[] { return allTokens; } @@ -86,8 +52,8 @@ namespace ts.formatting { public isSpecific() { return false; } } - export class TokenAllExceptAccess implements ITokenAccess { - constructor(readonly except: SyntaxKind) {} + class TokenAllExceptAccess implements TokenRange { + constructor(private readonly except: SyntaxKind) {} public GetTokens(): SyntaxKind[] { return allTokens.filter(t => t !== this.except); @@ -100,55 +66,58 @@ namespace ts.formatting { public isSpecific() { return false; } } - export class TokenRange { - constructor(public tokenAccess: ITokenAccess) { + export interface TokenRange { + GetTokens(): SyntaxKind[]; + Contains(token: SyntaxKind): boolean; + isSpecific(): boolean; + } + + export namespace TokenRange { + export function FromToken(token: SyntaxKind): TokenRange { + return new TokenSingleValueAccess(token); } - static FromToken(token: SyntaxKind): TokenRange { - return new TokenRange(new TokenSingleValueAccess(token)); + export function FromTokens(tokens: SyntaxKind[]): TokenRange { + return new TokenValuesAccess(tokens); } - static FromTokens(tokens: SyntaxKind[]): TokenRange { - return new TokenRange(new TokenValuesAccess(tokens)); + export function FromRange(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[] = []): TokenRange { + const tokens: SyntaxKind[] = []; + for (let token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); } - static FromRange(f: SyntaxKind, to: SyntaxKind, except: SyntaxKind[] = []): TokenRange { - return new TokenRange(new TokenRangeAccess(f, to, except)); + export function AnyExcept(token: SyntaxKind): TokenRange { + return new TokenAllExceptAccess(token); } - static AnyExcept(token: SyntaxKind): TokenRange { - return new TokenRange(new TokenAllExceptAccess(token)); - } - - public GetTokens(): SyntaxKind[] { - return this.tokenAccess.GetTokens(); - } - - public Contains(token: SyntaxKind): boolean { - return this.tokenAccess.Contains(token); - } - - public toString(): string { - return this.tokenAccess.toString(); - } - - public isSpecific() { - return this.tokenAccess.isSpecific(); - } - - static Any: TokenRange = new TokenRange(new TokenAllAccess()); - static AnyIncludingMultilineComments = TokenRange.FromTokens([...allTokens, SyntaxKind.MultiLineCommentTrivia]); - static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); - static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); - static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]); - static UnaryPrefixOperators = TokenRange.FromTokens([SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]); - static UnaryPrefixExpressions = TokenRange.FromTokens([SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); - static UnaryPreincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); - static UnaryPostincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); - static UnaryPredecrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); - static UnaryPostdecrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); - static Comments = TokenRange.FromTokens([SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia]); - static TypeNames = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]); + export const Any: TokenRange = new TokenAllAccess(); + export const AnyIncludingMultilineComments = TokenRange.FromTokens([...allTokens, SyntaxKind.MultiLineCommentTrivia]); + export const Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); + export const BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); + export const BinaryKeywordOperators = TokenRange.FromTokens([ + SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]); + export const UnaryPrefixOperators = TokenRange.FromTokens([ + SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]); + export const UnaryPrefixExpressions = TokenRange.FromTokens([ + SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, + SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); + export const UnaryPreincrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); + export const UnaryPostincrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); + export const UnaryPredecrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); + export const UnaryPostdecrementExpressions = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); + export const Comments = TokenRange.FromTokens([SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia]); + export const TypeNames = TokenRange.FromTokens([ + SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword, + SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]); } } } From 48773435382b47aecb8947fb37e440d0e69a061d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 3 May 2017 10:10:13 -0700 Subject: [PATCH 053/282] Reduce max number of spelling suggestions to 10 --- src/compiler/checker.ts | 2 +- .../maximum100SpellingSuggestions.errors.txt | 378 ------------------ .../maximum100SpellingSuggestions.js | 140 ------- .../maximum10SpellingSuggestions.errors.txt | 45 +++ .../reference/maximum10SpellingSuggestions.js | 24 ++ .../reference/parserRealSource11.errors.txt | 156 ++++---- .../reference/parserRealSource7.errors.txt | 8 +- .../reference/parserS7.6_A4.2_T1.errors.txt | 92 ++--- .../reference/parserharness.errors.txt | 140 +++---- .../reference/parserindenter.errors.txt | 8 +- .../reference/scannerS7.6_A4.2_T1.errors.txt | 92 ++--- .../compiler/maximum100SpellingSuggestions.ts | 14 - .../compiler/maximum10SpellingSuggestions.ts | 5 + 13 files changed, 323 insertions(+), 781 deletions(-) delete mode 100644 tests/baselines/reference/maximum100SpellingSuggestions.errors.txt delete mode 100644 tests/baselines/reference/maximum100SpellingSuggestions.js create mode 100644 tests/baselines/reference/maximum10SpellingSuggestions.errors.txt create mode 100644 tests/baselines/reference/maximum10SpellingSuggestions.js delete mode 100644 tests/cases/compiler/maximum100SpellingSuggestions.ts create mode 100644 tests/cases/compiler/maximum10SpellingSuggestions.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ca9ac8e09ea..ebf33f166cd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -319,7 +319,7 @@ namespace ts { const resolutionPropertyNames: TypeSystemPropertyName[] = []; let suggestionCount = 0; - const maximumSuggestionCount = 100; + const maximumSuggestionCount = 10; const mergedSymbols: Symbol[] = []; const symbolLinks: SymbolLinks[] = []; const nodeLinks: NodeLinks[] = []; diff --git a/tests/baselines/reference/maximum100SpellingSuggestions.errors.txt b/tests/baselines/reference/maximum100SpellingSuggestions.errors.txt deleted file mode 100644 index 4f921104d77..00000000000 --- a/tests/baselines/reference/maximum100SpellingSuggestions.errors.txt +++ /dev/null @@ -1,378 +0,0 @@ -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(3,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(4,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(5,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(6,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(7,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(8,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(9,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(10,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(11,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,1): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,6): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,11): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,16): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,26): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,31): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,36): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,41): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(12,46): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,1): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,6): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,11): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,16): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,21): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,26): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,31): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,36): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,41): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(13,46): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,1): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,6): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,11): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,16): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,21): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,26): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,31): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,36): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,41): error TS2304: Cannot find name 'any'. -tests/cases/compiler/maximum100SpellingSuggestions.ts(14,46): error TS2304: Cannot find name 'any'. - - -==== tests/cases/compiler/maximum100SpellingSuggestions.ts (120 errors) ==== - // 10 anys per line, 12 lines - // the last two lines should not have spelling suggestions - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - any; any; any; any; any; any; any; any; any; any; - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - ~~~ -!!! error TS2304: Cannot find name 'any'. - \ No newline at end of file diff --git a/tests/baselines/reference/maximum100SpellingSuggestions.js b/tests/baselines/reference/maximum100SpellingSuggestions.js deleted file mode 100644 index 5746091feb1..00000000000 --- a/tests/baselines/reference/maximum100SpellingSuggestions.js +++ /dev/null @@ -1,140 +0,0 @@ -//// [maximum100SpellingSuggestions.ts] -// 10 anys per line, 12 lines -// the last two lines should not have spelling suggestions -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; - - -//// [maximum100SpellingSuggestions.js] -// 10 anys per line, 12 lines -// the last two lines should not have spelling suggestions -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; -any; diff --git a/tests/baselines/reference/maximum10SpellingSuggestions.errors.txt b/tests/baselines/reference/maximum10SpellingSuggestions.errors.txt new file mode 100644 index 00000000000..8069d7bd1f5 --- /dev/null +++ b/tests/baselines/reference/maximum10SpellingSuggestions.errors.txt @@ -0,0 +1,45 @@ +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,1): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,6): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,11): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,16): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,21): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,26): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,31): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,36): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,41): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(4,46): error TS2552: Cannot find name 'bob'. Did you mean 'blob'? +tests/cases/compiler/maximum10SpellingSuggestions.ts(5,1): error TS2304: Cannot find name 'bob'. +tests/cases/compiler/maximum10SpellingSuggestions.ts(5,6): error TS2304: Cannot find name 'bob'. + + +==== tests/cases/compiler/maximum10SpellingSuggestions.ts (12 errors) ==== + // 10 bobs on the first line + // the last two bobs should not have did-you-mean spelling suggestions + var blob; + bob; bob; bob; bob; bob; bob; bob; bob; bob; bob; + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + ~~~ +!!! error TS2552: Cannot find name 'bob'. Did you mean 'blob'? + bob; bob; + ~~~ +!!! error TS2304: Cannot find name 'bob'. + ~~~ +!!! error TS2304: Cannot find name 'bob'. + \ No newline at end of file diff --git a/tests/baselines/reference/maximum10SpellingSuggestions.js b/tests/baselines/reference/maximum10SpellingSuggestions.js new file mode 100644 index 00000000000..eedd55b0840 --- /dev/null +++ b/tests/baselines/reference/maximum10SpellingSuggestions.js @@ -0,0 +1,24 @@ +//// [maximum10SpellingSuggestions.ts] +// 10 bobs on the first line +// the last two bobs should not have did-you-mean spelling suggestions +var blob; +bob; bob; bob; bob; bob; bob; bob; bob; bob; bob; +bob; bob; + + +//// [maximum10SpellingSuggestions.js] +// 10 bobs on the first line +// the last two bobs should not have did-you-mean spelling suggestions +var blob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; +bob; diff --git a/tests/baselines/reference/parserRealSource11.errors.txt b/tests/baselines/reference/parserRealSource11.errors.txt index ee15d465ea0..ba52fa5b62d 100644 --- a/tests/baselines/reference/parserRealSource11.errors.txt +++ b/tests/baselines/reference/parserRealSource11.errors.txt @@ -107,13 +107,13 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(487,58): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(489,22): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(491,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(494,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(496,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(496,58): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(498,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(500,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(500,58): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(502,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(504,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(504,58): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(506,22): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(507,58): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(507,58): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(518,32): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(520,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(525,27): error TS2304: Cannot find name 'Signature'. @@ -174,26 +174,26 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(644,21): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(647,26): error TS2304: Cannot find name 'tokenTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(651,58): error TS2304: Cannot find name 'tokenTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(658,26): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(660,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(660,67): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(665,26): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(669,26): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(670,55): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(672,33): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(672,60): error TS2304: Cannot find name 'FncFlags'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(678,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(681,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(684,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(678,67): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(681,67): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(684,63): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(686,26): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(687,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(694,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(687,63): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(694,63): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(696,26): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(711,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(714,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(718,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(718,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(721,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(723,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(725,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(721,51): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(723,51): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(725,51): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(733,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(738,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(747,30): error TS2304: Cannot find name 'Emitter'. @@ -213,7 +213,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(837,30): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(837,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(838,24): error TS2304: Cannot find name 'ModuleType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(841,61): error TS2304: Cannot find name 'TypeSymbol'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(850,52): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(850,52): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(863,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(867,29): error TS1015: Parameter cannot have question mark and initializer. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(868,38): error TS2304: Cannot find name 'NodeType'. @@ -311,7 +311,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1164,47): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1164,97): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1172,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1172,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1176,60): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1176,60): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1187,32): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1195,27): error TS2304: Cannot find name 'ModuleFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1196,21): error TS2304: Cannot find name 'ModuleType'. @@ -354,7 +354,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1339,26): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1348,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1351,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1351,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1362,67): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1362,67): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1374,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1375,37): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1388,36): error TS2304: Cannot find name 'TypeFlow'. @@ -370,7 +370,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1438,34): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1457,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1462,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1462,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1467,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1467,47): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1475,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1479,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1481,33): error TS2304: Cannot find name 'BasicBlock'. @@ -380,7 +380,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1490,39): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1515,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1518,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1518,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1528,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1528,47): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1535,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1539,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1541,33): error TS2304: Cannot find name 'BasicBlock'. @@ -389,7 +389,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1545,29): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1572,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1577,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1577,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1583,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1583,47): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1596,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1600,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1602,31): error TS2304: Cannot find name 'BasicBlock'. @@ -398,7 +398,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1615,39): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1651,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1654,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1654,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1660,63): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1660,63): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1670,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1675,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1682,19): error TS2304: Cannot find name 'NodeType'. @@ -416,8 +416,8 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1732,66): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1733,73): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1749,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1749,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1755,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1757,46): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1755,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1757,46): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1766,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1775,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1784,33): error TS2304: Cannot find name 'BasicBlock'. @@ -426,10 +426,10 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1811,19): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1816,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1816,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1822,43): error TS2304: Cannot find name 'NodeType'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1823,55): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1827,65): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1831,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1833,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1823,55): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1827,65): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1831,47): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1833,47): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1841,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1845,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1850,33): error TS2304: Cannot find name 'BasicBlock'. @@ -443,13 +443,13 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1908,25): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1911,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1914,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1914,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1919,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1919,51): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1928,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1939,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1944,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1944,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1950,46): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1958,50): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1950,46): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1958,50): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1969,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1981,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1984,33): error TS2304: Cannot find name 'BasicBlock'. @@ -457,7 +457,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(1985,35): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2014,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2017,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2017,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2022,51): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2022,51): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2033,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2042,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2043,33): error TS2304: Cannot find name 'BasicBlock'. @@ -466,12 +466,12 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2067,19): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2070,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2070,48): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2074,36): error TS2304: Cannot find name 'TypeFlow'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2077,28): error TS2552: Cannot find name 'getTypeLink'. Did you mean 'typeLink'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2077,28): error TS2304: Cannot find name 'getTypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2100,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2105,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2105,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2107,50): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2108,54): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2107,50): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2108,54): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2112,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2119,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2120,36): error TS2304: Cannot find name 'BasicBlock'. @@ -479,8 +479,8 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2122,32): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2145,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2150,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2150,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2153,50): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2154,52): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2153,50): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2154,52): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2159,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2161,32): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2164,37): error TS2304: Cannot find name 'BasicBlock'. @@ -489,7 +489,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2185,36): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2195,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2198,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2198,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2202,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2202,47): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2207,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2212,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2223,19): error TS2304: Cannot find name 'NodeType'. @@ -497,8 +497,8 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2225,40): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2229,32): error TS2304: Cannot find name 'SymbolScope'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2231,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2231,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2237,48): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2240,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2237,48): error TS2304: Cannot find name 'TokenID'. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2240,47): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2245,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2248,36): error TS2304: Cannot find name 'BasicBlock'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2259,36): error TS2304: Cannot find name 'TypeFlow'. @@ -508,7 +508,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2269,38): error tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2300,19): error TS2304: Cannot find name 'NodeType'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2303,30): error TS2304: Cannot find name 'Emitter'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2303,48): error TS2304: Cannot find name 'TokenID'. -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2307,47): error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2307,47): error TS2304: Cannot find name 'TokenID'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2312,42): error TS2304: Cannot find name 'ControlFlowContext'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2320,36): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2331,19): error TS2304: Cannot find name 'NodeType'. @@ -1233,7 +1233,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("typeof "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. break; case NodeType.Delete: ~~~~~~~~ @@ -1241,7 +1241,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("delete "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. break; case NodeType.Void: ~~~~~~~~ @@ -1249,14 +1249,14 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("void "); emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. break; case NodeType.TypeAssertion: ~~~~~~~~ !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. break; default: throw new Error("please implement in derived class"); @@ -1531,7 +1531,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error if (!emitter.tryEmitConstant(this)) { emitter.emitJavascript(this.operand1, TokenID.Dot, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput("."); emitter.emitJavascriptName(this.operand2, false); } @@ -1561,24 +1561,24 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand1, TokenID.Colon, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. } else { emitter.emitJavascript(this.operand1, TokenID.Colon, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutputTrimmable(": "); } emitter.emitJavascript(this.operand2, TokenID.Comma, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. break; case NodeType.Comma: ~~~~~~~~ !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.operand1, TokenID.Comma, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. if (emitter.emitState.inObjectLiteral) { emitter.writeLineToOutput(", "); } @@ -1587,7 +1587,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error } emitter.emitJavascript(this.operand2, TokenID.Comma, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. break; case NodeType.Is: ~~~~~~~~ @@ -1626,15 +1626,15 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascript(this.operand1, TokenID.Question, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(" ? "); emitter.emitJavascript(this.operand2, TokenID.Question, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(" : "); emitter.emitJavascript(this.operand3, TokenID.Question, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -1799,7 +1799,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.firstModAlias = this.firstAliasedModToString(); emitter.emitJavascript(this.alias, TokenID.Tilde, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. // the dynamic import case will insert the semi-colon automatically if (!this.isDynamicImport) { emitter.writeToOutput(";"); @@ -2321,7 +2321,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascriptList(this.bod, null, TokenID.Semicolon, true, false, false, true, this.requiresInherits); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -2593,7 +2593,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error if (this.statements) { emitter.emitJavascriptList(this.statements, null, TokenID.Semicolon, true, false, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. } if (this.isStatementBlock) { emitter.indenter.decreaseIndent(); @@ -2730,7 +2730,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("while("); emitter.emitJavascript(this.cond, TokenID.While, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(")"); emitter.emitJavascriptStatements(this.body, false, false); emitter.setInObjectLiteral(temp); @@ -2811,7 +2811,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput('('); emitter.emitJavascript(this.cond, TokenID.CloseParen, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(")"); emitter.setInObjectLiteral(temp); emitter.recordSourceMappingEnd(this); @@ -2884,7 +2884,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("if("); emitter.emitJavascript(this.cond, TokenID.If, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.emitJavascriptStatements(this.thenBod, true, false); @@ -2979,7 +2979,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("return "); emitter.emitJavascript(this.returnExpression, TokenID.Semicolon, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. } else { emitter.writeToOutput("return;"); @@ -3110,11 +3110,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("for("); emitter.emitJavascript(this.lval, TokenID.For, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(" in "); emitter.emitJavascript(this.obj, TokenID.For, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.emitJavascriptStatements(this.body, true, false); @@ -3198,23 +3198,23 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error !!! error TS2304: Cannot find name 'NodeType'. emitter.emitJavascript(this.init, TokenID.For, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. } else { emitter.setInVarBlock((this.init).members.length); emitter.emitJavascriptList(this.init, null, TokenID.For, false, false, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. } } emitter.writeToOutput("; "); emitter.emitJavascript(this.cond, TokenID.For, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput("; "); emitter.emitJavascript(this.incr, TokenID.For, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(")"); emitter.emitJavascriptStatements(this.body, true, false); emitter.setInObjectLiteral(temp); @@ -3328,7 +3328,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error if (this.expr) { emitter.emitJavascript(this.expr, TokenID.With, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. } emitter.writeToOutput(")"); @@ -3369,7 +3369,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("switch("); emitter.emitJavascript(this.val, TokenID.Identifier, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.writeLineToOutput(" {"); @@ -3379,7 +3379,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error var caseExpr = this.caseList.members[i]; emitter.emitJavascript(caseExpr, TokenID.Case, true); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeLineToOutput(""); } emitter.indenter.decreaseIndent(); @@ -3459,7 +3459,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("case "); emitter.emitJavascript(this.expr, TokenID.Identifier, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. } else { emitter.writeToOutput("default"); @@ -3532,7 +3532,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error typeFlow.inTypeRefTypeCheck = true; var typeLink = getTypeLink(this, typeFlow.checker, true); ~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'getTypeLink'. Did you mean 'typeLink'? +!!! error TS2304: Cannot find name 'getTypeLink'. typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); if (this.term) { @@ -3570,10 +3570,10 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascript(this.tryNode, TokenID.Try, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.emitJavascript(this.finallyNode, TokenID.Finally, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.recordSourceMappingEnd(this); } @@ -3634,10 +3634,10 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.recordSourceMappingStart(this); emitter.emitJavascript(this.tryNode, TokenID.Try, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.emitJavascript(this.catchNode, TokenID.Catch, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -3703,7 +3703,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("try "); emitter.emitJavascript(this.body, TokenID.Try, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -3754,12 +3754,12 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("catch ("); emitter.emitJavascript(this.param, TokenID.OpenParen, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.writeToOutput(")"); emitter.recordSourceMappingEnd(this.statement); emitter.emitJavascript(this.body, TokenID.Catch, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } @@ -3846,7 +3846,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error emitter.writeToOutput("finally"); emitter.emitJavascript(this.body, TokenID.Finally, false); ~~~~~~~ -!!! error TS2552: Cannot find name 'TokenID'. Did you mean 'tokenId'? +!!! error TS2304: Cannot find name 'TokenID'. emitter.recordSourceMappingEnd(this); emitter.emitParensAndCommentsInPlace(this, false); } diff --git a/tests/baselines/reference/parserRealSource7.errors.txt b/tests/baselines/reference/parserRealSource7.errors.txt index 67f3f5e9a28..4e30bfe075f 100644 --- a/tests/baselines/reference/parserRealSource7.errors.txt +++ b/tests/baselines/reference/parserRealSource7.errors.txt @@ -196,7 +196,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(476,57): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(477,29): error TS2304: Cannot find name 'ValueLocation'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,29): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,55): error TS2304: Cannot find name 'VarFlags'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2304: Cannot find name 'FieldSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,34): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,60): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(492,30): error TS2304: Cannot find name 'getTypeLink'. @@ -218,7 +218,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,26): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,52): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(518,22): error TS2304: Cannot find name 'FieldSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(531,29): error TS2304: Cannot find name 'ValueLocation'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2304: Cannot find name 'FieldSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,53): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,75): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(539,38): error TS2304: Cannot find name 'SymbolFlags'. @@ -1181,7 +1181,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(argDecl.id.text, argDecl.minChar, ~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? +!!! error TS2304: Cannot find name 'FieldSymbol'. context.checker.locationInfo.unitIndex, !hasFlag(argDecl.varFlags, VarFlags.Readonly), ~~~~~~~ @@ -1278,7 +1278,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(varDecl.id.text, varDecl.minChar, ~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? +!!! error TS2304: Cannot find name 'FieldSymbol'. context.checker.locationInfo.unitIndex, (varDecl.varFlags & VarFlags.Readonly) == VarFlags.None, ~~~~~~~~ diff --git a/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt b/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt index c63ee2056b7..53865fd69ab 100644 --- a/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt +++ b/tests/baselines/reference/parserS7.6_A4.2_T1.errors.txt @@ -8,29 +8,29 @@ tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(38,3): error TS tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(42,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(46,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(50,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(54,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(58,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(62,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(66,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(70,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(74,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(78,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(82,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(86,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(90,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(94,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(98,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(102,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(106,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(110,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(114,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(118,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(122,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(126,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(130,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(134,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(138,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(142,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(54,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(58,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(62,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(66,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(70,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(74,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(78,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(82,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(86,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(90,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(94,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(98,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(102,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(106,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(110,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(114,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(118,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(122,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(126,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(130,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(134,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(138,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(142,3): error TS2304: Cannot find name '$ERROR'. ==== tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts (33 errors) ==== @@ -109,139 +109,139 @@ tests/cases/conformance/parser/ecmascript5/parserS7.6_A4.2_T1.ts(142,3): error T if (К !== 1) { $ERROR('#К'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041B = 1; if (Л !== 1) { $ERROR('#Л'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041C = 1; if (М !== 1) { $ERROR('#М'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041D = 1; if (Н !== 1) { $ERROR('#Н'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041E = 1; if (О !== 1) { $ERROR('#О'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041F = 1; if (П !== 1) { $ERROR('#П'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0420 = 1; if (Р !== 1) { $ERROR('#Р'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0421 = 1; if (С !== 1) { $ERROR('#С'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0422 = 1; if (Т !== 1) { $ERROR('#Т'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0423 = 1; if (У !== 1) { $ERROR('#У'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0424 = 1; if (Ф !== 1) { $ERROR('#Ф'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0425 = 1; if (Х !== 1) { $ERROR('#Х'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0426 = 1; if (Ц !== 1) { $ERROR('#Ц'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0427 = 1; if (Ч !== 1) { $ERROR('#Ч'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0428 = 1; if (Ш !== 1) { $ERROR('#Ш'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0429 = 1; if (Щ !== 1) { $ERROR('#Щ'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042A = 1; if (Ъ !== 1) { $ERROR('#Ъ'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042B = 1; if (Ы !== 1) { $ERROR('#Ы'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042C = 1; if (Ь !== 1) { $ERROR('#Ь'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042D = 1; if (Э !== 1) { $ERROR('#Э'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042E = 1; if (Ю !== 1) { $ERROR('#Ю'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042F = 1; if (Я !== 1) { $ERROR('#Я'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0401 = 1; if (Ё !== 1) { $ERROR('#Ё'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index b9ac11d3b6c..d4aa6682c40 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -29,51 +29,51 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): e tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,115): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(999,40): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1041,43): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1044,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1045,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1046,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1047,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1048,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1049,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1050,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1051,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1052,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1053,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1055,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1058,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1044,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1045,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1046,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1047,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1048,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1049,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1050,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1051,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1052,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1053,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1055,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1058,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1059,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1061,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1064,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1061,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1064,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1065,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1067,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1070,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1067,26): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1070,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1071,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1073,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1073,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1074,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1076,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1076,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1077,34): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1079,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1079,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,35): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,74): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1107,173): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1176,132): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1193,29): error TS2552: Cannot find name 'WScript'. Did you mean 'scripts'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1193,29): error TS2304: Cannot find name 'WScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1256,126): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1257,25): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1263,31): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1280,45): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1280,45): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,124): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,209): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,142): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,227): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1302,43): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1304,39): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1307,38): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1311,45): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1321,21): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1302,43): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1304,39): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1307,38): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1311,45): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1321,21): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1340,38): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1344,165): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1345,26): error TS2503: Cannot find namespace 'TypeScript'. @@ -85,21 +85,21 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1461,23): tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1466,36): error TS2304: Cannot find name 'optionRegex'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1484,21): error TS2304: Cannot find name 'optionRegex'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1548,57): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1571,32): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1571,32): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1582,59): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1591,24): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1600,24): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1591,24): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1600,24): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1604,42): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1605,21): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1705,38): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1706,26): error TS2304: Cannot find name 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,62): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,87): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1714,30): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1724,34): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1739,20): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1714,30): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1724,34): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1739,20): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1746,80): error TS2503: Cannot find namespace 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1750,26): error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1750,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1758,84): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1769,51): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,39): error TS2503: Cannot find namespace 'Services'. @@ -107,7 +107,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,61): tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1785,25): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,38): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,68): error TS2503: Cannot find namespace 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): error TS2552: Cannot find name 'Diff'. Did you mean 'diff'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): error TS2304: Cannot find name 'Diff'. ==== tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts (110 errors) ==== @@ -1162,7 +1162,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? var entries = new TypeScript.ScopeTraversal(compiler).getScopeEntries(enclosingScopeContext); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. for (var i = 0; i < entries.length; i++) { if (entries[i].name === targetIdentifier) { @@ -1224,88 +1224,88 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): switch (ast.nodeType) { case TypeScript.NodeType.Name: // Type Name? ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.Null: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.List: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.Empty: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.EmptyExpr: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.Asg: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.True: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.False: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.ArrayLit: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. case TypeScript.NodeType.TypeRef: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. break; case TypeScript.NodeType.Super: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = (ast).text; break; case TypeScript.NodeType.Regex: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = (ast).text; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.QString: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = (ast).text; break; case TypeScript.NodeType.NumberLit: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = (ast).text; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.Return: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. //name = (tyInfo.ast).returnExpression.actualText; // why is this complaining? break; case TypeScript.NodeType.InterfaceDeclaration: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = (ast).name.actualText; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.ModuleDeclaration: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = (ast).name.actualText; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.ClassDeclaration: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = (ast).name.actualText; ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.FuncDecl: ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. name = !(ast).name ? "" : (ast).name.actualText; // name == null for lambdas ~~~~~~~~~~ !!! error TS2503: Cannot find namespace 'TypeScript'. @@ -1429,7 +1429,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): else { WScript.Echo("non-match on: " + errorLines[i]); ~~~~~~~ -!!! error TS2552: Cannot find name 'WScript'. Did you mean 'scripts'? +!!! error TS2304: Cannot find name 'WScript'. } } } @@ -1524,7 +1524,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): if (Harness.usePull) { compiler.pullUpdateUnit(new TypeScript.StringSourceText(code), unitName, setRecovery); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. } else { compiler.updateUnit(code, unitName, setRecovery); } @@ -1556,22 +1556,22 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var oldCompilerSettings = new TypeScript.CompilationSettings(); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. clone(compiler.settings, oldCompilerSettings); var oldEmitSettings = new TypeScript.EmitOptions(compiler.settings); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. clone(compiler.emitSettings, oldEmitSettings); var oldModuleGenTarget = TypeScript.moduleGenTarget; ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. if (settingsCallback) { settingsCallback(compiler.settings); compiler.emitSettings = new TypeScript.EmitOptions(compiler.settings); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. } try { compileString(code, filename, callback, context, references); @@ -1583,7 +1583,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): compiler.emitSettings = oldEmitSettings; TypeScript.moduleGenTarget = oldModuleGenTarget; ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. } } } @@ -1857,7 +1857,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): length: this.content.length, editRange: new TypeScript.ScriptEditRange(minChar, limChar, (limChar - minChar) + newText.length) ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. }); if (this.editRanges.length > this.maxScriptVersions) { @@ -1881,7 +1881,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // Too far away from what we know return TypeScript.ScriptEditRange.unknown(); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. } var entries = this.editRanges.slice(initialEditRangeIndex); @@ -1892,7 +1892,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): return new TypeScript.ScriptEditRange(minDistFromStart, entries[0].length - minDistFromEnd, aggDelta); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. } } @@ -2020,7 +2020,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2503: Cannot find namespace 'TypeScript'. var parser = new TypeScript.Parser(); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. parser.setErrorRecovery(null); parser.errorCallback = (a, b, c, d) => { }; @@ -2032,7 +2032,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): public parseFile(fileName: string) { var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName)) ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. return this.parseSourceText(fileName, sourceText); } @@ -2049,7 +2049,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): return TypeScript.getPositionFromZeroBasedLineColumn(script, line - 1, col - 1); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. } /** @@ -2064,7 +2064,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var result = TypeScript.getZeroBasedLineColumnFromPosition(script, position); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'TypeScript'. Did you mean 'TypeScriptLS'? +!!! error TS2304: Cannot find name 'TypeScript'. assert.is(result.line >= 0); assert.is(result.col >= 0); @@ -2360,7 +2360,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // Append diff to the report var diff = new Diff.StringDiff(expected, actual); ~~~~ -!!! error TS2552: Cannot find name 'Diff'. Did you mean 'diff'? +!!! error TS2304: Cannot find name 'Diff'. var header = '

' + descriptionForDescribe + '

'; header += '

Left file: ' + actualFilename + '; Right file: ' + refFilename + '

'; var trailer = '
'; diff --git a/tests/baselines/reference/parserindenter.errors.txt b/tests/baselines/reference/parserindenter.errors.txt index 5e97bfdabc1..2f51281e7aa 100644 --- a/tests/baselines/reference/parserindenter.errors.txt +++ b/tests/baselines/reference/parserindenter.errors.txt @@ -112,8 +112,8 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(634,21): tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(665,34): error TS2304: Cannot find name 'IndentationEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(686,45): error TS2304: Cannot find name 'TextEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(688,34): error TS2304: Cannot find name 'IndentationEditInfo'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(695,35): error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(698,39): error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(695,35): error TS2304: Cannot find name 'IndentationEditInfo'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(698,39): error TS2304: Cannot find name 'IndentationEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(706,42): error TS2304: Cannot find name 'TextEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(709,50): error TS2304: Cannot find name 'TokenSpan'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(709,67): error TS2304: Cannot find name 'ParseNode'. @@ -1053,12 +1053,12 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): indentationInfo = IndentationEditInfo.create2(indent.Position, indent.ReplaceWith, lineStartPosition, lineIndentLength); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? +!!! error TS2304: Cannot find name 'IndentationEditInfo'. } else { indentationInfo = new IndentationEditInfo(indent); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'IndentationEditInfo'. Did you mean 'indentationInfo'? +!!! error TS2304: Cannot find name 'IndentationEditInfo'. } this.indentationBag.AddIndent(indentationInfo); diff --git a/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt b/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt index 6d850d8567f..0213122e54f 100644 --- a/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt +++ b/tests/baselines/reference/scannerS7.6_A4.2_T1.errors.txt @@ -8,29 +8,29 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(38,3): error tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(42,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(46,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(50,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(54,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(58,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(62,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(66,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(70,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(74,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(78,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(82,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(86,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(90,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(94,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(98,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(102,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(106,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(110,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(114,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(118,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(122,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(126,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(130,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(134,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(138,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? -tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(142,3): error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(54,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(58,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(62,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(66,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(70,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(74,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(78,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(82,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(86,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(90,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(94,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(98,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(102,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(106,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(110,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(114,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(118,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(122,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(126,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(130,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(134,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(138,3): error TS2304: Cannot find name '$ERROR'. +tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(142,3): error TS2304: Cannot find name '$ERROR'. ==== tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts (33 errors) ==== @@ -109,139 +109,139 @@ tests/cases/conformance/scanner/ecmascript5/scannerS7.6_A4.2_T1.ts(142,3): error if (К !== 1) { $ERROR('#К'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041B = 1; if (Л !== 1) { $ERROR('#Л'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041C = 1; if (М !== 1) { $ERROR('#М'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041D = 1; if (Н !== 1) { $ERROR('#Н'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041E = 1; if (О !== 1) { $ERROR('#О'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u041F = 1; if (П !== 1) { $ERROR('#П'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0420 = 1; if (Р !== 1) { $ERROR('#Р'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0421 = 1; if (С !== 1) { $ERROR('#С'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0422 = 1; if (Т !== 1) { $ERROR('#Т'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0423 = 1; if (У !== 1) { $ERROR('#У'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0424 = 1; if (Ф !== 1) { $ERROR('#Ф'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0425 = 1; if (Х !== 1) { $ERROR('#Х'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0426 = 1; if (Ц !== 1) { $ERROR('#Ц'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0427 = 1; if (Ч !== 1) { $ERROR('#Ч'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0428 = 1; if (Ш !== 1) { $ERROR('#Ш'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0429 = 1; if (Щ !== 1) { $ERROR('#Щ'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042A = 1; if (Ъ !== 1) { $ERROR('#Ъ'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042B = 1; if (Ы !== 1) { $ERROR('#Ы'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042C = 1; if (Ь !== 1) { $ERROR('#Ь'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042D = 1; if (Э !== 1) { $ERROR('#Э'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042E = 1; if (Ю !== 1) { $ERROR('#Ю'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u042F = 1; if (Я !== 1) { $ERROR('#Я'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } var \u0401 = 1; if (Ё !== 1) { $ERROR('#Ё'); ~~~~~~ -!!! error TS2552: Cannot find name '$ERROR'. Did you mean 'Error'? +!!! error TS2304: Cannot find name '$ERROR'. } \ No newline at end of file diff --git a/tests/cases/compiler/maximum100SpellingSuggestions.ts b/tests/cases/compiler/maximum100SpellingSuggestions.ts deleted file mode 100644 index febc10c1c6f..00000000000 --- a/tests/cases/compiler/maximum100SpellingSuggestions.ts +++ /dev/null @@ -1,14 +0,0 @@ -// 10 anys per line, 12 lines -// the last two lines should not have spelling suggestions -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; -any; any; any; any; any; any; any; any; any; any; diff --git a/tests/cases/compiler/maximum10SpellingSuggestions.ts b/tests/cases/compiler/maximum10SpellingSuggestions.ts new file mode 100644 index 00000000000..7aa27dc1e2a --- /dev/null +++ b/tests/cases/compiler/maximum10SpellingSuggestions.ts @@ -0,0 +1,5 @@ +// 10 bobs on the first line +// the last two bobs should not have did-you-mean spelling suggestions +var blob; +bob; bob; bob; bob; bob; bob; bob; bob; bob; bob; +bob; bob; From 9bf520963227929ce9a3868c0b5ba894b224dc36 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 3 May 2017 10:46:00 -0700 Subject: [PATCH 054/282] Lower allowed length difference for suggestions And update baselines --- src/compiler/checker.ts | 2 +- .../reference/innerModExport2.errors.txt | 4 ++-- .../reference/parser15.4.4.14-9-2.errors.txt | 4 ++-- .../reference/parserRealSource7.errors.txt | 16 ++++++++-------- ...rRegularExpressionDivideAmbiguity1.errors.txt | 4 ++-- ...rRegularExpressionDivideAmbiguity2.errors.txt | 4 ++-- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ebf33f166cd..1008c411474 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14205,7 +14205,7 @@ namespace ts { */ function getSpellingSuggestionForName(name: string, symbols: Symbol[], meaning: SymbolFlags): Symbol | undefined { const worstDistance = name.length * 0.4; - const maximumLengthDifference = Math.min(4, name.length * 0.34); + const maximumLengthDifference = Math.min(3, name.length * 0.34); let bestDistance = Number.MAX_VALUE; let bestCandidate = undefined; if (name.length > 30) { diff --git a/tests/baselines/reference/innerModExport2.errors.txt b/tests/baselines/reference/innerModExport2.errors.txt index edd22daca41..f9568bb45a4 100644 --- a/tests/baselines/reference/innerModExport2.errors.txt +++ b/tests/baselines/reference/innerModExport2.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/innerModExport2.ts(5,5): error TS2304: Cannot find name 'mo tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected. tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. -tests/cases/compiler/innerModExport2.ts(20,7): error TS2551: Property 'NonExportFunc' does not exist on type 'typeof Outer'. Did you mean 'ExportFunc'? +tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExportFunc' does not exist on type 'typeof Outer'. ==== tests/cases/compiler/innerModExport2.ts (5 errors) ==== @@ -35,4 +35,4 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2551: Property 'NonExport Outer.NonExportFunc(); ~~~~~~~~~~~~~ -!!! error TS2551: Property 'NonExportFunc' does not exist on type 'typeof Outer'. Did you mean 'ExportFunc'? \ No newline at end of file +!!! error TS2339: Property 'NonExportFunc' does not exist on type 'typeof Outer'. \ No newline at end of file diff --git a/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt b/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt index 143592f649a..2c721724b3e 100644 --- a/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt +++ b/tests/baselines/reference/parser15.4.4.14-9-2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(16,15): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate 'false'. -tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(25,1): error TS2552: Cannot find name 'runTestCase'. Did you mean 'testcase'? +tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(25,1): error TS2304: Cannot find name 'runTestCase'. ==== tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts (2 errors) ==== @@ -33,5 +33,5 @@ tests/cases/conformance/parser/ecmascript5/parser15.4.4.14-9-2.ts(25,1): error T } runTestCase(testcase); ~~~~~~~~~~~ -!!! error TS2552: Cannot find name 'runTestCase'. Did you mean 'testcase'? +!!! error TS2304: Cannot find name 'runTestCase'. \ No newline at end of file diff --git a/tests/baselines/reference/parserRealSource7.errors.txt b/tests/baselines/reference/parserRealSource7.errors.txt index 4e30bfe075f..1261d7b5f06 100644 --- a/tests/baselines/reference/parserRealSource7.errors.txt +++ b/tests/baselines/reference/parserRealSource7.errors.txt @@ -71,7 +71,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,48): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,66): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,90): error TS2304: Cannot find name 'StringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(206,113): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(207,31): error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(207,31): error TS2304: Cannot find name 'ModuleType'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(209,42): error TS2304: Cannot find name 'TypeFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(211,39): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(211,57): error TS2304: Cannot find name 'DualStringHashTable'. @@ -100,7 +100,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(250,82): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(251,38): error TS2304: Cannot find name 'ScopedMembers'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(251,56): error TS2304: Cannot find name 'DualStringHashTable'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(251,107): error TS2304: Cannot find name 'StringHashTable'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(253,27): error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(253,27): error TS2304: Cannot find name 'ModuleType'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(255,38): error TS2304: Cannot find name 'TypeFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(272,33): error TS2304: Cannot find name 'SymbolFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(276,33): error TS2304: Cannot find name 'SymbolFlags'. @@ -196,7 +196,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(476,57): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(477,29): error TS2304: Cannot find name 'ValueLocation'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,29): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(478,55): error TS2304: Cannot find name 'VarFlags'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(480,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,34): error TS2304: Cannot find name 'hasFlag'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(482,60): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(492,30): error TS2304: Cannot find name 'getTypeLink'. @@ -218,7 +218,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,26): error T tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(507,52): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(518,22): error TS2304: Cannot find name 'FieldSymbol'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(531,29): error TS2304: Cannot find name 'ValueLocation'. -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2304: Cannot find name 'FieldSymbol'. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(533,21): error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,53): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(535,75): error TS2304: Cannot find name 'VarFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(539,38): error TS2304: Cannot find name 'SymbolFlags'. @@ -658,7 +658,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T !!! error TS2304: Cannot find name 'StringHashTable'. modType = new ModuleType(enclosedTypes, ambientEnclosedTypes); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? +!!! error TS2304: Cannot find name 'ModuleType'. if (isEnum) { modType.typeFlags |= TypeFlags.IsEnum; ~~~~~~~~~ @@ -762,7 +762,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T modType = new ModuleType(enclosedTypes, ambientEnclosedTypes); ~~~~~~~~~~ -!!! error TS2552: Cannot find name 'ModuleType'. Did you mean 'modType'? +!!! error TS2304: Cannot find name 'ModuleType'. if (isEnum) { modType.typeFlags |= TypeFlags.IsEnum; ~~~~~~~~~ @@ -1181,7 +1181,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(argDecl.id.text, argDecl.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, !hasFlag(argDecl.varFlags, VarFlags.Readonly), ~~~~~~~ @@ -1278,7 +1278,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T var fieldSymbol = new FieldSymbol(varDecl.id.text, varDecl.minChar, ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'FieldSymbol'. +!!! error TS2552: Cannot find name 'FieldSymbol'. Did you mean 'fieldSymbol'? context.checker.locationInfo.unitIndex, (varDecl.varFlags & VarFlags.Readonly) == VarFlags.None, ~~~~~~~~ diff --git a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt index cf1bd1fd2e2..ab0c1dc4d2e 100644 --- a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt +++ b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity1.ts(2,2): error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity1.ts(2,2): error TS2304: Cannot find name 'notregexp'. tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity1.ts(2,12): error TS2304: Cannot find name 'a'. @@ -6,6 +6,6 @@ tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpre 1 /notregexp/a.foo(); ~~~~~~~~~ -!!! error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? +!!! error TS2304: Cannot find name 'notregexp'. ~ !!! error TS2304: Cannot find name 'a'. \ No newline at end of file diff --git a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt index cfe5b118ee5..eac54ef0fe4 100644 --- a/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt +++ b/tests/baselines/reference/parserRegularExpressionDivideAmbiguity2.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts(1,6): error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts(1,6): error TS2304: Cannot find name 'notregexp'. tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts(1,16): error TS2304: Cannot find name 'a'. ==== tests/cases/conformance/parser/ecmascript5/RegularExpressions/parserRegularExpressionDivideAmbiguity2.ts (2 errors) ==== (1) /notregexp/a.foo(); ~~~~~~~~~ -!!! error TS2552: Cannot find name 'notregexp'. Did you mean 'RegExp'? +!!! error TS2304: Cannot find name 'notregexp'. ~ !!! error TS2304: Cannot find name 'a'. \ No newline at end of file From 99c18744d231fdce63f92951197388a8eb17ee0e Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 3 May 2017 10:57:57 -0700 Subject: [PATCH 055/282] Add isCallOrNewExpression helper --- src/compiler/checker.ts | 3 ++- src/compiler/utilities.ts | 4 ++++ src/services/formatting/smartIndenter.ts | 5 +---- src/services/signatureHelp.ts | 2 +- src/services/symbolDisplay.ts | 2 +- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b6ff059380e..61503415d81 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14310,7 +14310,8 @@ namespace ts { } function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression { - return node.kind === SyntaxKind.CallExpression || node.kind === SyntaxKind.NewExpression; + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return isCallOrNewExpression(node); } function resolveUntypedCall(node: CallLikeExpression): Signature { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5314bdacb43..b9b1dbb2a13 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1142,6 +1142,10 @@ namespace ts { } } + export function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression { + return node.kind === SyntaxKind.CallExpression || node.kind === SyntaxKind.NewExpression; + } + export function getInvokedExpression(node: CallLikeExpression): Expression { if (node.kind === SyntaxKind.TaggedTemplateExpression) { return (node).tag; diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 01feaf39081..18b0479c85a 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -341,10 +341,7 @@ namespace ts.formatting { return Value.Unknown; } - if (node.parent && ( - node.parent.kind === SyntaxKind.CallExpression || - node.parent.kind === SyntaxKind.NewExpression) && - (node.parent).expression !== node) { + if (node.parent && isCallOrNewExpression(node.parent) && (node.parent).expression !== node) { const fullCallOrNewExpression = (node.parent).expression; const startingExpression = getStartingExpression(fullCallOrNewExpression); diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 1487bb410a5..7c4f8fb016d 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -262,7 +262,7 @@ namespace ts.SignatureHelp { * in the argument of an invocation; returns undefined otherwise. */ export function getImmediatelyContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile): ArgumentListInfo { - if (node.parent.kind === SyntaxKind.CallExpression || node.parent.kind === SyntaxKind.NewExpression) { + if (isCallOrNewExpression(node.parent)) { const callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 41bdf4d8ada..5bf3e37f28a 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -120,7 +120,7 @@ namespace ts.SymbolDisplay { // try get the call/construct signature from the type if it matches let callExpressionLike: CallExpression | NewExpression | JsxOpeningLikeElement; - if (location.kind === SyntaxKind.CallExpression || location.kind === SyntaxKind.NewExpression) { + if (isCallOrNewExpression(location)) { callExpressionLike = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { From 5ce32ccbe3ef50101f7d1745a4bf64a7eb7a88ff Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 3 May 2017 13:13:28 -0700 Subject: [PATCH 056/282] factor out helpers + cleanup `startsWith` and friends --- src/compiler/core.ts | 13 +++++++++---- src/compiler/moduleNameResolver.ts | 15 ++++++++++++++- src/services/codefixes/importFixes.ts | 10 ++-------- src/services/pathCompletions.ts | 15 ++++++--------- 4 files changed, 31 insertions(+), 22 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 321cc06f765..2f945fb7526 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1730,13 +1730,18 @@ namespace ts { /* @internal */ export function startsWith(str: string, prefix: string): boolean { - return str.lastIndexOf(prefix, 0) === 0; + return str.indexOf(prefix) === 0; + } + + /* @internal */ + export function removePrefix(str: string, prefix: string | undefined): string { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; } /* @internal */ export function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + return expectedPos >= 0 && str.lastIndexOf(suffix, expectedPos) === expectedPos; } export function hasExtension(fileName: string): boolean { @@ -1747,7 +1752,7 @@ namespace ts { return path.length > extension.length && endsWith(path, extension); } - export function fileExtensionIsAny(path: string, extensions: string[]): boolean { + export function fileExtensionIsOneOf(path: string, extensions: string[]): boolean { for (const extension of extensions) { if (fileExtensionIs(path, extension)) { return true; @@ -1947,7 +1952,7 @@ namespace ts { for (const current of files) { const name = combinePaths(path, current); const absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) continue; + if (extensions && !fileExtensionIsOneOf(name, extensions)) continue; if (excludeRegex && excludeRegex.test(absoluteName)) continue; if (!includeFileRegexes) { results[0].push(name); diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index d511b31b331..b1d0f2ab7b2 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -958,10 +958,13 @@ namespace ts { } } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + const mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ function mangleScopedPackage(moduleName: string, state: ModuleResolutionState): string { if (startsWith(moduleName, "@")) { - const replaceSlash = moduleName.replace(ts.directorySeparator, "__"); + const replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== moduleName) { const mangled = replaceSlash.slice(1); // Take off the "@" if (state.traceEnabled) { @@ -973,6 +976,16 @@ namespace ts { return moduleName; } + export function getPackageNameFromAtTypesDirectory(mangledName: string): string { + const withoutAtTypePrefix = removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf("__") !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost): SearchResult { const result = cache && cache.get(containingDirectory); if (result) { diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 7885fe66c2a..b91ee2a3041 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -501,14 +501,6 @@ namespace ts.codefix { relativeFileName = getRelativePath(moduleFileName, sourceDirectory); } - if (startsWith(relativeFileName, "@types/")) { - relativeFileName = relativeFileName.substr(/*"@types".length*/ 7); - if (relativeFileName.indexOf("__") !== -1) { - // Double underscores are used in DefinitelyTyped to delimit scoped packages. - relativeFileName = "@" + relativeFileName.replace("__", "/"); - } - } - relativeFileName = removeFileExtension(relativeFileName); if (endsWith(relativeFileName, "/index")) { relativeFileName = getDirectoryPath(relativeFileName); @@ -530,6 +522,8 @@ namespace ts.codefix { catch (e) { } } + relativeFileName = getPackageNameFromAtTypesDirectory(relativeFileName); + return relativeFileName; } } diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 2b45457c147..e97c3e0c655 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -245,18 +245,15 @@ namespace ts.Completions.PathCompletions { // Get modules that the type checker picked up const ambientModules = map(typeChecker.getAmbientModules(), sym => stripQuotes(sym.name)); - let nonRelativeModules = filter(ambientModules, moduleName => startsWith(moduleName, fragment)); + let nonRelativeModuleNames = filter(ambientModules, moduleName => startsWith(moduleName, fragment)); // Nested modules of the form "module-name/sub" need to be adjusted to only return the string // after the last '/' that appears in the fragment because that's where the replacement span // starts if (isNestedModule) { const moduleNameWithSeperator = ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModules = map(nonRelativeModules, moduleName => { - if (startsWith(fragment, moduleNameWithSeperator)) { - return moduleName.substr(moduleNameWithSeperator.length); - } - return moduleName; + nonRelativeModuleNames = map(nonRelativeModuleNames, nonRelativeModuleName => { + return removePrefix(nonRelativeModuleName, moduleNameWithSeperator); }); } @@ -264,7 +261,7 @@ namespace ts.Completions.PathCompletions { if (!options.moduleResolution || options.moduleResolution === ModuleResolutionKind.NodeJs) { for (const visibleModule of enumerateNodeModulesVisibleToScript(host, scriptPath)) { if (!isNestedModule) { - nonRelativeModules.push(visibleModule.moduleName); + nonRelativeModuleNames.push(visibleModule.moduleName); } else if (startsWith(visibleModule.moduleName, moduleNameFragment)) { const nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); @@ -272,14 +269,14 @@ namespace ts.Completions.PathCompletions { for (let f of nestedFiles) { f = normalizePath(f); const nestedModule = removeFileExtension(getBaseFileName(f)); - nonRelativeModules.push(nestedModule); + nonRelativeModuleNames.push(nestedModule); } } } } } - return deduplicate(nonRelativeModules); + return deduplicate(nonRelativeModuleNames); } export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): CompletionInfo { From 69e7841cda3045a03a596ef0b8506bd3e4e99a69 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 3 May 2017 13:22:01 -0700 Subject: [PATCH 057/282] revert noop change --- src/compiler/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 2f945fb7526..6de1d62c14e 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1741,7 +1741,7 @@ namespace ts { /* @internal */ export function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.lastIndexOf(suffix, expectedPos) === expectedPos; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } export function hasExtension(fileName: string): boolean { From d38ee1eaf71fb6f92418ba5c2bf53b7b08366a17 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 3 May 2017 13:26:24 -0700 Subject: [PATCH 058/282] restore `startsWith` --- src/compiler/core.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 6de1d62c14e..de560d89d40 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1729,8 +1729,8 @@ namespace ts { } /* @internal */ - export function startsWith(str: string, prefix: string): boolean { - return str.indexOf(prefix) === 0; + export function startsWith(str: string, prefix: string | undefined): boolean { + return str.lastIndexOf(prefix, 0) === 0; } /* @internal */ From 5eff8c206bc9c937564078676990778b694e0486 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 3 May 2017 13:29:24 -0700 Subject: [PATCH 059/282] revert core changes --- src/compiler/core.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index de560d89d40..654e6b00c1a 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1729,12 +1729,12 @@ namespace ts { } /* @internal */ - export function startsWith(str: string, prefix: string | undefined): boolean { + export function startsWith(str: string, prefix: string): boolean { return str.lastIndexOf(prefix, 0) === 0; } /* @internal */ - export function removePrefix(str: string, prefix: string | undefined): string { + export function removePrefix(str: string, prefix: string): string { return startsWith(str, prefix) ? str.substr(prefix.length) : str; } From 0b68b934ef5983314e71e57ed461da7785af4808 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 3 May 2017 13:30:53 -0700 Subject: [PATCH 060/282] respond to comments --- src/services/codefixes/importFixes.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index b91ee2a3041..99aaec476cd 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -522,9 +522,7 @@ namespace ts.codefix { catch (e) { } } - relativeFileName = getPackageNameFromAtTypesDirectory(relativeFileName); - - return relativeFileName; + return getPackageNameFromAtTypesDirectory(relativeFileName); } } From 2a7398b12a57db0c2f5030a6183f4d399a1913c9 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 3 May 2017 14:04:09 -0700 Subject: [PATCH 061/282] Include primitives in type-as-value error message Previously, you would get the generic message when writing incorrect code like `let y = number`. "Cannot find name 'number'". Now the message says "'number' is a type but is used a value here." Fixes #15565 --- src/compiler/checker.ts | 4 ++++ .../baselines/reference/autoLift2.errors.txt | 8 ++++---- .../reference/badArrayIndex.errors.txt | 4 ++-- tests/baselines/reference/bases.errors.txt | 8 ++++---- ...annotInvokeNewOnIndexExpression.errors.txt | 4 ++-- .../classExtendingPrimitive.errors.txt | 12 +++++------ .../classExtendsEveryObjectType.errors.txt | 4 ++-- .../classExtendsEveryObjectType2.errors.txt | 4 ++-- ...assMemberWithMissingIdentifier2.errors.txt | 4 ++-- .../reference/complicatedPrivacy.errors.txt | 4 ++-- ...torWithIncompleteTypeAnnotation.errors.txt | 20 +++++++++---------- .../reference/createArray.errors.txt | 12 +++++------ ...orLocationForInterfaceExtension.errors.txt | 4 ++-- .../newExpressionWithCast.errors.txt | 4 ++-- .../reference/newNonReferenceType.errors.txt | 8 ++++---- .../reference/newOperator.errors.txt | 12 +++++------ ...adingStaticFunctionsInFunctions.errors.txt | 8 ++++---- .../reference/parserRealSource10.errors.txt | 12 +++++------ .../parserUnterminatedGeneric2.errors.txt | 12 +++++------ .../primitiveTypeAssignment.errors.txt | 12 +++++------ .../reference/privateIndexer2.errors.txt | 4 ++-- .../reference/staticsInAFunction.errors.txt | 8 ++++---- .../thisTypeInFunctionsNegative.errors.txt | 4 ++-- .../reference/typeAssertions.errors.txt | 8 ++++---- .../reference/undeclaredVarEmit.errors.txt | 4 ++-- 25 files changed, 96 insertions(+), 92 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1008c411474..44ff0561779 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1236,6 +1236,10 @@ namespace ts { function checkAndReportErrorForUsingTypeAsValue(errorLocation: Node, name: string, meaning: SymbolFlags): boolean { if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "void" || name === "never") { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & SymbolFlags.NamespaceModule)) { error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); diff --git a/tests/baselines/reference/autoLift2.errors.txt b/tests/baselines/reference/autoLift2.errors.txt index 1111a3750d8..4e07c1c92f5 100644 --- a/tests/baselines/reference/autoLift2.errors.txt +++ b/tests/baselines/reference/autoLift2.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/autoLift2.ts(5,14): error TS2339: Property 'foo' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(5,17): error TS1005: ';' expected. -tests/cases/compiler/autoLift2.ts(5,19): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/autoLift2.ts(5,19): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/autoLift2.ts(6,14): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? tests/cases/compiler/autoLift2.ts(6,17): error TS1005: ';' expected. -tests/cases/compiler/autoLift2.ts(6,19): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/autoLift2.ts(6,19): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/autoLift2.ts(12,11): error TS2339: Property 'foo' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(14,11): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? tests/cases/compiler/autoLift2.ts(16,33): error TS2339: Property 'foo' does not exist on type 'A'. @@ -21,14 +21,14 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2551: Property 'bar' does not ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. this.bar: any; ~~~ !!! error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } diff --git a/tests/baselines/reference/badArrayIndex.errors.txt b/tests/baselines/reference/badArrayIndex.errors.txt index 12aec4d45f4..decfebeeac7 100644 --- a/tests/baselines/reference/badArrayIndex.errors.txt +++ b/tests/baselines/reference/badArrayIndex.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/badArrayIndex.ts(1,15): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/compiler/badArrayIndex.ts(1,15): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/badArrayIndex.ts(1,22): error TS1109: Expression expected. ==== tests/cases/compiler/badArrayIndex.ts (2 errors) ==== var results = number[]; ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~ !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/bases.errors.txt b/tests/baselines/reference/bases.errors.txt index 974d5accfc4..3069f977fe1 100644 --- a/tests/baselines/reference/bases.errors.txt +++ b/tests/baselines/reference/bases.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/bases.ts(7,14): error TS2339: Property 'y' does not exist on type 'B'. tests/cases/compiler/bases.ts(7,15): error TS1005: ';' expected. -tests/cases/compiler/bases.ts(7,17): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/bases.ts(7,17): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/bases.ts(11,7): error TS2420: Class 'C' incorrectly implements interface 'I'. Property 'x' is missing in type 'C'. tests/cases/compiler/bases.ts(12,5): error TS2377: Constructors for derived classes must contain a 'super' call. tests/cases/compiler/bases.ts(13,9): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/bases.ts(13,14): error TS2339: Property 'x' does not exist on type 'C'. tests/cases/compiler/bases.ts(13,15): error TS1005: ';' expected. -tests/cases/compiler/bases.ts(13,17): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/bases.ts(13,17): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/bases.ts(17,9): error TS2339: Property 'x' does not exist on type 'C'. tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist on type 'C'. @@ -25,7 +25,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } } @@ -44,7 +44,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } ~~~~~ !!! error TS2377: Constructors for derived classes must contain a 'super' call. diff --git a/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt b/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt index 5e1b869c057..dbd10d775d9 100644 --- a/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt +++ b/tests/baselines/reference/cannotInvokeNewOnIndexExpression.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2693: 'any' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts (1 errors) ==== var test: any[] = new any[1]; ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? \ No newline at end of file +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendingPrimitive.errors.txt b/tests/baselines/reference/classExtendingPrimitive.errors.txt index fc2e5bd5ad7..32a3e68cb3e 100644 --- a/tests/baselines/reference/classExtendingPrimitive.errors.txt +++ b/tests/baselines/reference/classExtendingPrimitive.errors.txt @@ -1,6 +1,6 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2552: Cannot find name 'number'. Did you mean 'Number'? -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2552: Cannot find name 'string'. Did you mean 'String'? -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2693: 'number' only refers to a type, but is being used as a value here. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2693: 'string' only refers to a type, but is being used as a value here. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2693: 'boolean' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(6,18): error TS2304: Cannot find name 'Void'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(7,19): error TS1109: Expression expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(8,18): error TS2304: Cannot find name 'Null'. @@ -14,13 +14,13 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla class C extends number { } ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. class C2 extends string { } ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. class C3 extends boolean { } ~~~~~~~ -!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. class C4 extends Void { } ~~~~ !!! error TS2304: Cannot find name 'Void'. diff --git a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt index 7c624b3b284..b4e8aa7360e 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(4,17): error TS2689: Cannot extend an interface 'I'. Did you mean 'implements'? tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,31): error TS1005: ',' expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(8,18): error TS2507: Type '{ foo: string; }' is not a constructor function type. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(11,18): error TS2507: Type 'typeof M' is not a constructor function type. @@ -20,7 +20,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla ~~~~~~~~~~~~~~~~ !!! error TS2507: Type '{ foo: any; }' is not a constructor function type. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. var x: { foo: string; } diff --git a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt index e92761884ea..bbaac166582 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,31): error TS1005: ',' expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(3,18): error TS2507: Type 'undefined[]' is not a constructor function type. @@ -9,7 +9,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla ~~~~~~~~~~~~~~~~ !!! error TS2507: Type '{ foo: any; }' is not a constructor function type. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. diff --git a/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt index d0459214fd1..9854a115aa6 100644 --- a/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt +++ b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,11): error TS1146: D tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,12): error TS1005: '=' expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,14): error TS2304: Cannot find name 'name'. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,18): error TS1005: ']' expected. -tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,25): error TS1005: ',' expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,26): error TS1136: Property assignment expected. tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: Cannot find name 'VariableDeclaration'. @@ -20,7 +20,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: C ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/complicatedPrivacy.errors.txt b/tests/baselines/reference/complicatedPrivacy.errors.txt index ccf0b4fa025..661b0693807 100644 --- a/tests/baselines/reference/complicatedPrivacy.errors.txt +++ b/tests/baselines/reference/complicatedPrivacy.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/complicatedPrivacy.ts(11,24): error TS1054: A 'get' accessor cannot have parameters. tests/cases/compiler/complicatedPrivacy.ts(35,5): error TS1170: A computed property name in a type literal must directly refer to a built-in symbol. -tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo5' has no exported member 'i6'. @@ -45,7 +45,7 @@ tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo ~~~~~~~~ !!! error TS1170: A computed property name in a type literal must directly refer to a built-in symbol. ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. }) { } diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 1f561036035..9a36bb405ab 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -52,7 +52,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,9): error TS tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,16): error TS2304: Cannot find name 'method1'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2552: Cannot find name 'val'. Did you mean 'eval'? tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,27): error TS1005: ',' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,36): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,9): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,16): error TS2304: Cannot find name 'method2'. @@ -67,14 +67,14 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,9): error TS tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2304: Cannot find name 'Overloads'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2304: Cannot find name 'value'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,31): error TS1005: ',' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,9): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2304: Cannot find name 'Overloads'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,27): error TS1135: Argument expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,33): error TS1005: '(' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,43): error TS1109: Expression expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,60): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,65): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,9): error TS2304: Cannot find name 'public'. @@ -82,7 +82,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error T tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS2304: Cannot find name 'DefaultValue'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2304: Cannot find name 'value'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,35): error TS1109: Expression expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,55): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS1128: Declaration or statement expected. @@ -435,7 +435,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. return val; @@ -486,7 +486,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. public Overloads( while : string, ...rest: string[]) { & ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -497,11 +497,11 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1005: '(' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~~ !!! error TS1109: Expression expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. ~ @@ -519,7 +519,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~ !!! error TS1109: Expression expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/createArray.errors.txt b/tests/baselines/reference/createArray.errors.txt index e562abd282c..082e8dc03e2 100644 --- a/tests/baselines/reference/createArray.errors.txt +++ b/tests/baselines/reference/createArray.errors.txt @@ -1,16 +1,16 @@ -tests/cases/compiler/createArray.ts(1,12): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/compiler/createArray.ts(1,12): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/createArray.ts(1,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/compiler/createArray.ts(6,6): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/createArray.ts(7,12): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +tests/cases/compiler/createArray.ts(7,12): error TS2693: 'boolean' only refers to a type, but is being used as a value here. tests/cases/compiler/createArray.ts(7,19): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/createArray.ts(8,12): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/createArray.ts(8,12): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. ==== tests/cases/compiler/createArray.ts (7 errors) ==== var na=new number[]; ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. @@ -22,12 +22,12 @@ tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be use !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var ba=new boolean[]; ~~~~~~~ -!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var sa=new string[]; ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. function f(s:string):number { return 0; diff --git a/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt b/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt index f385d0afcb3..6ed1517335d 100644 --- a/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt +++ b/tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/errorLocationForInterfaceExtension.ts(3,21): error TS2304: Cannot find name 'string'. +tests/cases/compiler/errorLocationForInterfaceExtension.ts(3,21): error TS2693: 'string' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/errorLocationForInterfaceExtension.ts (1 errors) ==== @@ -6,5 +6,5 @@ tests/cases/compiler/errorLocationForInterfaceExtension.ts(3,21): error TS2304: interface x extends string { } ~~~~~~ -!!! error TS2304: Cannot find name 'string'. +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/newExpressionWithCast.errors.txt b/tests/baselines/reference/newExpressionWithCast.errors.txt index 158856f7beb..5a2e18c585f 100644 --- a/tests/baselines/reference/newExpressionWithCast.errors.txt +++ b/tests/baselines/reference/newExpressionWithCast.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/newExpressionWithCast.ts(3,12): error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type. tests/cases/compiler/newExpressionWithCast.ts(7,13): error TS2365: Operator '>' cannot be applied to types 'boolean' and 'void'. tests/cases/compiler/newExpressionWithCast.ts(7,17): error TS1109: Expression expected. -tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2693: 'any' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/newExpressionWithCast.ts (4 errors) ==== @@ -19,7 +19,7 @@ tests/cases/compiler/newExpressionWithCast.ts(7,18): error TS2552: Cannot find n ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. function Test3() { } // valid with noImplicitAny diff --git a/tests/baselines/reference/newNonReferenceType.errors.txt b/tests/baselines/reference/newNonReferenceType.errors.txt index 4cf478b6e22..01824a64f5f 100644 --- a/tests/baselines/reference/newNonReferenceType.errors.txt +++ b/tests/baselines/reference/newNonReferenceType.errors.txt @@ -1,12 +1,12 @@ -tests/cases/compiler/newNonReferenceType.ts(1,13): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/newNonReferenceType.ts(2,13): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +tests/cases/compiler/newNonReferenceType.ts(1,13): error TS2693: 'any' only refers to a type, but is being used as a value here. +tests/cases/compiler/newNonReferenceType.ts(2,13): error TS2693: 'boolean' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/newNonReferenceType.ts (2 errors) ==== var a = new any(); ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. var b = new boolean(); // error ~~~~~~~ -!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/newOperator.errors.txt b/tests/baselines/reference/newOperator.errors.txt index 6c07677acd3..ae96023a60b 100644 --- a/tests/baselines/reference/newOperator.errors.txt +++ b/tests/baselines/reference/newOperator.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/newOperator.ts(3,13): error TS2693: 'ifc' only refers to a type, but is being used as a value here. tests/cases/compiler/newOperator.ts(10,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/compiler/newOperator.ts(11,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -tests/cases/compiler/newOperator.ts(12,5): error TS2552: Cannot find name 'string'. Did you mean 'String'? -tests/cases/compiler/newOperator.ts(18,14): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/newOperator.ts(12,5): error TS2693: 'string' only refers to a type, but is being used as a value here. +tests/cases/compiler/newOperator.ts(18,14): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/newOperator.ts(18,20): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/compiler/newOperator.ts(21,1): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/newOperator.ts(21,1): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/newOperator.ts(22,1): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/compiler/newOperator.ts(28,13): error TS2304: Cannot find name 'q'. tests/cases/compiler/newOperator.ts(31,10): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. @@ -32,7 +32,7 @@ tests/cases/compiler/newOperator.ts(45,23): error TS1150: 'new T[]' cannot be us !!! error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. new string; ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. // Use in LHS of expression? (new Date()).toString(); @@ -40,14 +40,14 @@ tests/cases/compiler/newOperator.ts(45,23): error TS1150: 'new T[]' cannot be us // Various spacing var t3 = new string[]( ); ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. var t4 = new string ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. [ ~ ] diff --git a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt index 4aa261d9808..cded9c44a3d 100644 --- a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt +++ b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt @@ -5,12 +5,12 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,3): error TS1128 tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,19): error TS1005: ',' expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,3): error TS1128: Declaration or statement expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,20): error TS1109: Expression expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,21): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,21): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS1005: ';' expected. @@ -33,7 +33,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. static test(name?:any){ } ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -44,7 +44,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/parserRealSource10.errors.txt b/tests/baselines/reference/parserRealSource10.errors.txt index c6ab397d7d7..7d65c1690fe 100644 --- a/tests/baselines/reference/parserRealSource10.errors.txt +++ b/tests/baselines/reference/parserRealSource10.errors.txt @@ -1,11 +1,11 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,33): error TS2449: Class 'TokenInfo' used before its declaration. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,36): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,36): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,41): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,41): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(129,47): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,35): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,35): error TS2693: 'boolean' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(130,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(179,54): error TS2304: Cannot find name 'ErrorRecoverySet'. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(184,28): error TS2304: Cannot find name 'ErrorRecoverySet'. @@ -479,17 +479,17 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(449,40): error !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var nodeTypeTable = new string[]; ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var nodeTypeToTokTable = new number[]; ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. export var noRegexTable = new boolean[]; ~~~~~~~ -!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. ~~ !!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. diff --git a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt index 2b663a8cd4f..e38a548f34c 100644 --- a/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt +++ b/tests/baselines/reference/parserUnterminatedGeneric2.errors.txt @@ -4,12 +4,12 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,9): error TS2304: Cannot find name 'assign'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,16): error TS2304: Cannot find name 'context'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,23): error TS1005: ',' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,25): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,25): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,30): error TS2304: Cannot find name 'value'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,35): error TS1005: ',' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,37): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,37): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,41): error TS1005: ';' expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,43): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(4,43): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,23): error TS2304: Cannot find name 'IPromise'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,45): error TS2304: Cannot find name 'IPromise'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGeneric2.ts(8,54): error TS1005: '>' expected. @@ -33,17 +33,17 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnterminatedGener ~ !!! error TS1005: ',' expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~~~~~ !!! error TS2304: Cannot find name 'value'. ~ !!! error TS1005: ',' expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. } interface IQService { diff --git a/tests/baselines/reference/primitiveTypeAssignment.errors.txt b/tests/baselines/reference/primitiveTypeAssignment.errors.txt index 4048a00150f..1800e1657e0 100644 --- a/tests/baselines/reference/primitiveTypeAssignment.errors.txt +++ b/tests/baselines/reference/primitiveTypeAssignment.errors.txt @@ -1,18 +1,18 @@ -tests/cases/compiler/primitiveTypeAssignment.ts(1,9): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? -tests/cases/compiler/primitiveTypeAssignment.ts(3,9): error TS2552: Cannot find name 'number'. Did you mean 'Number'? -tests/cases/compiler/primitiveTypeAssignment.ts(5,9): error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +tests/cases/compiler/primitiveTypeAssignment.ts(1,9): error TS2693: 'any' only refers to a type, but is being used as a value here. +tests/cases/compiler/primitiveTypeAssignment.ts(3,9): error TS2693: 'number' only refers to a type, but is being used as a value here. +tests/cases/compiler/primitiveTypeAssignment.ts(5,9): error TS2693: 'boolean' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/primitiveTypeAssignment.ts (3 errors) ==== var x = any; ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. var y = number; ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. var z = boolean; ~~~~~~~ -!!! error TS2552: Cannot find name 'boolean'. Did you mean 'Boolean'? +!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here. \ No newline at end of file diff --git a/tests/baselines/reference/privateIndexer2.errors.txt b/tests/baselines/reference/privateIndexer2.errors.txt index a12da313ffa..7e826dbc7a9 100644 --- a/tests/baselines/reference/privateIndexer2.errors.txt +++ b/tests/baselines/reference/privateIndexer2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,15): error TS1005: ']' expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,23): error TS1005: ',' expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,24): error TS1136: Property assignment expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32): error TS1005: ':' expected. @@ -13,7 +13,7 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32) ~ !!! error TS1005: ']' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/staticsInAFunction.errors.txt b/tests/baselines/reference/staticsInAFunction.errors.txt index 46636037c97..254f321913b 100644 --- a/tests/baselines/reference/staticsInAFunction.errors.txt +++ b/tests/baselines/reference/staticsInAFunction.errors.txt @@ -5,12 +5,12 @@ tests/cases/compiler/staticsInAFunction.ts(3,4): error TS1128: Declaration or st tests/cases/compiler/staticsInAFunction.ts(3,11): error TS2304: Cannot find name 'test'. tests/cases/compiler/staticsInAFunction.ts(3,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(3,20): error TS1005: ',' expected. -tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/staticsInAFunction.ts(4,4): error TS1128: Declaration or statement expected. tests/cases/compiler/staticsInAFunction.ts(4,11): error TS2304: Cannot find name 'test'. tests/cases/compiler/staticsInAFunction.ts(4,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(4,21): error TS1109: Expression expected. -tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. @@ -33,7 +33,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~ !!! error TS1005: ',' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. static test(name?:any){} ~~~~~~ !!! error TS1128: Declaration or statement expected. @@ -44,7 +44,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~ !!! error TS1109: Expression expected. ~~~ -!!! error TS2552: Cannot find name 'any'. Did you mean 'NaN'? +!!! error TS2693: 'any' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt index c136d3dd573..a3771839dc5 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt @@ -91,7 +91,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,30): e tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,32): error TS1138: Parameter declaration expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,39): error TS1005: ';' expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,40): error TS1128: Declaration or statement expected. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,42): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,42): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,49): error TS1005: ';' expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,1): error TS7027: Unreachable code detected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,29): error TS2304: Cannot find name 'm'. @@ -425,7 +425,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e ~ !!! error TS1128: Declaration or statement expected. ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index bfc42321505..cdd576e6d8b 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -11,7 +11,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,5): erro tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS1005: '>' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS1005: ')' expected. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,48): error TS1005: ';' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(45,2): error TS2322: Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. @@ -19,7 +19,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,32): err tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS1005: ')' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS1005: ';' expected. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS2552: Cannot find name 'string'. Did you mean 'String'? +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): error TS1005: ';' expected. @@ -91,7 +91,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err ~~~~~~ !!! error TS1005: ')' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. str = numOrStr; // Error, no narrowing occurred @@ -110,7 +110,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2552: Cannot find name 'string'. Did you mean 'String'? +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/undeclaredVarEmit.errors.txt b/tests/baselines/reference/undeclaredVarEmit.errors.txt index 689360aa899..bbf508ab005 100644 --- a/tests/baselines/reference/undeclaredVarEmit.errors.txt +++ b/tests/baselines/reference/undeclaredVarEmit.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/undeclaredVarEmit.ts(1,1): error TS7028: Unused label. -tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2552: Cannot find name 'number'. Did you mean 'Number'? +tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2693: 'number' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/undeclaredVarEmit.ts (2 errors) ==== @@ -7,4 +7,4 @@ tests/cases/compiler/undeclaredVarEmit.ts(1,4): error TS2552: Cannot find name ' ~ !!! error TS7028: Unused label. ~~~~~~ -!!! error TS2552: Cannot find name 'number'. Did you mean 'Number'? \ No newline at end of file +!!! error TS2693: 'number' only refers to a type, but is being used as a value here. \ No newline at end of file From 7282b9f0ce4af2b20c39da6f89f41b8ae239ff81 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 3 May 2017 14:12:24 -0700 Subject: [PATCH 062/282] make internal --- src/compiler/core.ts | 1 + src/compiler/moduleNameResolver.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 654e6b00c1a..357bd0699e3 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1752,6 +1752,7 @@ namespace ts { return path.length > extension.length && endsWith(path, extension); } + /* @internal */ export function fileExtensionIsOneOf(path: string, extensions: string[]): boolean { for (const extension of extensions) { if (fileExtensionIs(path, extension)) { diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index b1d0f2ab7b2..5c2e2dcea8e 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -976,6 +976,7 @@ namespace ts { return moduleName; } + /* @internal */ export function getPackageNameFromAtTypesDirectory(mangledName: string): string { const withoutAtTypePrefix = removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { From 5a7e9676287c2fa966508f51dd70d9c9702bae18 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 3 May 2017 14:48:23 -0700 Subject: [PATCH 063/282] Blacklist some built-ins and improve max cutoff The maximum distance cutoff was being checked after the close-enough early exit. Now it's checked before. Note that `null` doesn't show up in the globals list, so it's not part of the blacklist either. --- src/compiler/checker.ts | 16 +++++++++++++--- ...ithExportedAndNonExportedFunctions.errors.txt | 4 ++-- .../VariableDeclaration11_es6.errors.txt | 4 ++-- .../VariableDeclaration6_es6.errors.txt | 4 ++-- tests/baselines/reference/autoLift2.errors.txt | 12 ++++++------ ...ructorWithIncompleteTypeAnnotation.errors.txt | 4 ++-- ...ashIntypeCheckInvocationExpression.errors.txt | 4 ++-- .../exportNonInitializedVariablesES6.errors.txt | 4 ++-- ...FromUsingES6FeaturesWithOnlyES5Lib.errors.txt | 4 ++-- .../tsxAttributeInvalidNames.errors.txt | 8 ++++---- ...thInstanceOfByConstructorSignature.errors.txt | 16 ++++++++-------- 11 files changed, 45 insertions(+), 35 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 44ff0561779..c57e925e17e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1236,7 +1236,7 @@ namespace ts { function checkAndReportErrorForUsingTypeAsValue(errorLocation: Node, name: string, meaning: SymbolFlags): boolean { if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule)) { - if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "void" || name === "never") { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); return true; } @@ -14224,14 +14224,24 @@ namespace ts { if (candidateName === name) { return candidate; } - if (candidateName.length < 3 || name.length < 3) { + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "Intl" || + candidateName === "undefined" || + candidateName === "Map" || + candidateName === "NaN" || + candidateName === "Set") { continue; } const distance = levenshtein(candidateName, name); + if (distance > worstDistance) { + continue; + } if (distance < 3) { return candidate; } - else if (distance < bestDistance && distance < worstDistance) { + else if (distance < bestDistance) { bestDistance = distance; bestCandidate = candidate; } diff --git a/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt b/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt index bf143b9224d..96864565d85 100644 --- a/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt +++ b/tests/baselines/reference/ModuleWithExportedAndNonExportedFunctions.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(28,13): error TS2551: Property 'fn2' does not exist on type 'typeof A'. Did you mean 'fng'? +tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(28,13): error TS2339: Property 'fn2' does not exist on type 'typeof A'. tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(29,14): error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'? @@ -32,7 +32,7 @@ tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAnd // these should be errors since the functions are not exported var fn2 = A.fn2; ~~~ -!!! error TS2551: Property 'fn2' does not exist on type 'typeof A'. Did you mean 'fng'? +!!! error TS2339: Property 'fn2' does not exist on type 'typeof A'. var fng2 = A.fng2; ~~~~ !!! error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'? \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration11_es6.errors.txt b/tests/baselines/reference/VariableDeclaration11_es6.errors.txt index 87650509cce..8fa0a99ab67 100644 --- a/tests/baselines/reference/VariableDeclaration11_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration11_es6.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS1212: Identifier expected. 'let' is a reserved word in strict mode. -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS2552: Cannot find name 'let'. Did you mean 'Set'? +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS2304: Cannot find name 'let'. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2, ~~~ !!! error TS1212: Identifier expected. 'let' is a reserved word in strict mode. ~~~ -!!! error TS2552: Cannot find name 'let'. Did you mean 'Set'? \ No newline at end of file +!!! error TS2304: Cannot find name 'let'. \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration6_es6.errors.txt b/tests/baselines/reference/VariableDeclaration6_es6.errors.txt index 440a2ee3ce5..fb2a41b8739 100644 --- a/tests/baselines/reference/VariableDeclaration6_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration6_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration6_es6.ts(1,1): error TS2552: Cannot find name 'let'. Did you mean 'Set'? +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration6_es6.ts(1,1): error TS2304: Cannot find name 'let'. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration6_es6.ts (1 errors) ==== let ~~~ -!!! error TS2552: Cannot find name 'let'. Did you mean 'Set'? \ No newline at end of file +!!! error TS2304: Cannot find name 'let'. \ No newline at end of file diff --git a/tests/baselines/reference/autoLift2.errors.txt b/tests/baselines/reference/autoLift2.errors.txt index 4e07c1c92f5..63d1c2c3548 100644 --- a/tests/baselines/reference/autoLift2.errors.txt +++ b/tests/baselines/reference/autoLift2.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/autoLift2.ts(5,14): error TS2339: Property 'foo' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(5,17): error TS1005: ';' expected. tests/cases/compiler/autoLift2.ts(5,19): error TS2693: 'any' only refers to a type, but is being used as a value here. -tests/cases/compiler/autoLift2.ts(6,14): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? +tests/cases/compiler/autoLift2.ts(6,14): error TS2339: Property 'bar' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(6,17): error TS1005: ';' expected. tests/cases/compiler/autoLift2.ts(6,19): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/autoLift2.ts(12,11): error TS2339: Property 'foo' does not exist on type 'A'. -tests/cases/compiler/autoLift2.ts(14,11): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? +tests/cases/compiler/autoLift2.ts(14,11): error TS2339: Property 'bar' does not exist on type 'A'. tests/cases/compiler/autoLift2.ts(16,33): error TS2339: Property 'foo' does not exist on type 'A'. -tests/cases/compiler/autoLift2.ts(18,33): error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? +tests/cases/compiler/autoLift2.ts(18,33): error TS2339: Property 'bar' does not exist on type 'A'. ==== tests/cases/compiler/autoLift2.ts (10 errors) ==== @@ -24,7 +24,7 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2551: Property 'bar' does not !!! error TS2693: 'any' only refers to a type, but is being used as a value here. this.bar: any; ~~~ -!!! error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? +!!! error TS2339: Property 'bar' does not exist on type 'A'. ~ !!! error TS1005: ';' expected. ~~~ @@ -40,7 +40,7 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2551: Property 'bar' does not this.bar = "bar"; ~~~ -!!! error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? +!!! error TS2339: Property 'bar' does not exist on type 'A'. [1, 2].forEach((p) => this.foo); ~~~ @@ -48,7 +48,7 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2551: Property 'bar' does not [1, 2].forEach((p) => this.bar); ~~~ -!!! error TS2551: Property 'bar' does not exist on type 'A'. Did you mean 'baz'? +!!! error TS2339: Property 'bar' does not exist on type 'A'. } diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 9a36bb405ab..1d37b20a3b3 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -50,7 +50,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(227,13): error T tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(234,14): error TS1005: '{' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,9): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,16): error TS2304: Cannot find name 'method1'. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2552: Cannot find name 'val'. Did you mean 'eval'? +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2304: Cannot find name 'val'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,27): error TS1005: ',' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2693: 'number' only refers to a type, but is being used as a value here. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,36): error TS1005: ';' expected. @@ -431,7 +431,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~~ !!! error TS2304: Cannot find name 'method1'. ~~~ -!!! error TS2552: Cannot find name 'val'. Did you mean 'eval'? +!!! error TS2304: Cannot find name 'val'. ~ !!! error TS1005: ',' expected. ~~~~~~ diff --git a/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt b/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt index e1bcb5fcb69..a1f5afbde13 100644 --- a/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt +++ b/tests/baselines/reference/crashIntypeCheckInvocationExpression.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(6,28): error TS2304: Cannot find name 'task'. -tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(8,18): error TS2552: Cannot find name 'path'. Did you mean 'Math'? +tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(8,18): error TS2304: Cannot find name 'path'. tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(9,19): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(10,50): error TS2304: Cannot find name 'moduleType'. @@ -16,7 +16,7 @@ tests/cases/compiler/crashIntypeCheckInvocationExpression.ts(10,50): error TS230 var folder = path.join(), ~~~~ -!!! error TS2552: Cannot find name 'path'. Did you mean 'Math'? +!!! error TS2304: Cannot find name 'path'. fileset = nake.fileSetSync(folder) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2347: Untyped function calls may not accept type arguments. diff --git a/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt b/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt index 60850c06b6d..84f9bcb59a4 100644 --- a/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt +++ b/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(1,4): error TS1123: Variable declaration list cannot be empty. tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(2,1): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. -tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(2,1): error TS2552: Cannot find name 'let'. Did you mean 'Set'? +tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(2,1): error TS2304: Cannot find name 'let'. tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(3,6): error TS1123: Variable declaration list cannot be empty. @@ -12,7 +12,7 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(3,6) ~~~ !!! error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. ~~~ -!!! error TS2552: Cannot find name 'let'. Did you mean 'Set'? +!!! error TS2304: Cannot find name 'let'. const; !!! error TS1123: Variable declaration list cannot be empty. diff --git a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt index 9b5f0ada58f..b56b03de533 100644 --- a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt +++ b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(4,18): error TS2339: Property 'from' does not exist on type 'ArrayConstructor'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(10,13): error TS2304: Cannot find name 'Map'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(17,5): error TS2339: Property 'name' does not exist on type '() => void'. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'asin'? +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(25,6): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(29,18): error TS2304: Cannot find name 'Symbol'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(33,13): error TS2304: Cannot find name 'Proxy'. @@ -40,7 +40,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.t // Using ES6 math Math.sign(1); ~~~~ -!!! error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'asin'? +!!! error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? // Using ES6 object var o = { diff --git a/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt b/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt index d6d7b2f277a..0607a01a11c 100644 --- a/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt +++ b/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt @@ -1,13 +1,13 @@ tests/cases/conformance/jsx/file.tsx(10,8): error TS1003: Identifier expected. tests/cases/conformance/jsx/file.tsx(10,10): error TS1005: ';' expected. -tests/cases/conformance/jsx/file.tsx(10,10): error TS2552: Cannot find name 'data'. Did you mean 'Date'? +tests/cases/conformance/jsx/file.tsx(10,10): error TS2304: Cannot find name 'data'. tests/cases/conformance/jsx/file.tsx(10,15): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/jsx/file.tsx(10,18): error TS1005: ':' expected. tests/cases/conformance/jsx/file.tsx(10,21): error TS1109: Expression expected. tests/cases/conformance/jsx/file.tsx(10,22): error TS1109: Expression expected. tests/cases/conformance/jsx/file.tsx(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/jsx/file.tsx(11,8): error TS1003: Identifier expected. -tests/cases/conformance/jsx/file.tsx(11,9): error TS2552: Cannot find name 'data'. Did you mean 'Date'? +tests/cases/conformance/jsx/file.tsx(11,9): error TS2304: Cannot find name 'data'. tests/cases/conformance/jsx/file.tsx(11,13): error TS1005: ';' expected. tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular expression literal. @@ -28,7 +28,7 @@ tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular ~~~~ !!! error TS1005: ';' expected. ~~~~ -!!! error TS2552: Cannot find name 'data'. Did you mean 'Date'? +!!! error TS2304: Cannot find name 'data'. ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. ~ @@ -43,7 +43,7 @@ tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular ~ !!! error TS1003: Identifier expected. ~~~~ -!!! error TS2552: Cannot find name 'data'. Did you mean 'Date'? +!!! error TS2304: Cannot find name 'data'. ~ !!! error TS1005: ';' expected. diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt index 096b19c3717..b93be614f74 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt @@ -3,14 +3,14 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(33,5): error TS2322: Type '"str"' is not assignable to type 'number'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(34,10): error TS2339: Property 'bar' does not exist on type 'B'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(41,10): error TS2339: Property 'bar' does not exist on type 'B'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(66,10): error TS2551: Property 'bar2' does not exist on type 'C1'. Did you mean 'bar1'? +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(66,10): error TS2339: Property 'bar2' does not exist on type 'C1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(72,10): error TS2339: Property 'bar1' does not exist on type 'C1 | C2'. Property 'bar1' does not exist on type 'C2'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(73,10): error TS2339: Property 'bar2' does not exist on type 'C1 | C2'. Property 'bar2' does not exist on type 'C1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(85,10): error TS2339: Property 'bar' does not exist on type 'D'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(91,10): error TS2339: Property 'bar' does not exist on type 'D'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(112,10): error TS2551: Property 'bar2' does not exist on type 'E1'. Did you mean 'bar1'? +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(112,10): error TS2339: Property 'bar2' does not exist on type 'E1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(118,11): error TS2339: Property 'bar1' does not exist on type 'E1 | E2'. Property 'bar1' does not exist on type 'E2'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(119,11): error TS2339: Property 'bar2' does not exist on type 'E1 | E2'. @@ -19,8 +19,8 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru Property 'foo' does not exist on type 'string'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(135,11): error TS2339: Property 'bar' does not exist on type 'string | F'. Property 'bar' does not exist on type 'string'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(160,11): error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(166,11): error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(160,11): error TS2339: Property 'foo2' does not exist on type 'G1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(166,11): error TS2339: Property 'foo2' does not exist on type 'G1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(182,11): error TS2339: Property 'bar' does not exist on type 'H'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(187,11): error TS2551: Property 'foo1' does not exist on type 'H'. Did you mean 'foo'? tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(188,11): error TS2551: Property 'foo2' does not exist on type 'H'. Did you mean 'foo'? @@ -104,7 +104,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj5.bar1; obj5.bar2; ~~~~ -!!! error TS2551: Property 'bar2' does not exist on type 'C1'. Did you mean 'bar1'? +!!! error TS2339: Property 'bar2' does not exist on type 'C1'. } var obj6: any; @@ -162,7 +162,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj9.bar1; obj9.bar2; ~~~~ -!!! error TS2551: Property 'bar2' does not exist on type 'E1'. Did you mean 'bar1'? +!!! error TS2339: Property 'bar2' does not exist on type 'E1'. } var obj10: any; @@ -224,7 +224,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj13.foo1; obj13.foo2; ~~~~ -!!! error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? +!!! error TS2339: Property 'foo2' does not exist on type 'G1'. } var obj14: any; @@ -232,7 +232,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj14.foo1; obj14.foo2; ~~~~ -!!! error TS2551: Property 'foo2' does not exist on type 'G1'. Did you mean 'foo1'? +!!! error TS2339: Property 'foo2' does not exist on type 'G1'. } // a type with a prototype that has any type From 34481640c5ea73087136c674c22622582001df90 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 3 May 2017 14:52:28 -0700 Subject: [PATCH 064/282] Obtain apparent type before narrowing type variables --- src/compiler/checker.ts | 42 ++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ca5d65068a0..9e24d6bb69e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5775,11 +5775,11 @@ namespace ts { const t = type.flags & TypeFlags.TypeVariable ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t) : t.flags & TypeFlags.StringLike ? globalStringType : - t.flags & TypeFlags.NumberLike ? globalNumberType : - t.flags & TypeFlags.BooleanLike ? globalBooleanType : - t.flags & TypeFlags.ESSymbol ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= ScriptTarget.ES2015) : - t.flags & TypeFlags.NonPrimitive ? emptyObjectType : - t; + t.flags & TypeFlags.NumberLike ? globalNumberType : + t.flags & TypeFlags.BooleanLike ? globalBooleanType : + t.flags & TypeFlags.ESSymbol ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= ScriptTarget.ES2015) : + t.flags & TypeFlags.NonPrimitive ? emptyObjectType : + t; } function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol { @@ -10439,11 +10439,13 @@ namespace ts { // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node: Node): string { if (node.kind === SyntaxKind.Identifier) { const symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === SyntaxKind.ThisKeyword) { return "0"; @@ -11708,6 +11710,28 @@ namespace ts { return annotationIncludesUndefined ? getTypeWithFacts(declaredType, TypeFacts.NEUndefined) : declaredType; } + function isApparentTypePosition(node: Node) { + // When a node is the left hand expression of a property access or call expression, the node occurs + // in an apparent type position. In such a position we fetch the apparent type of the node *before* + // performing control flow analysis such that, if the node is a type variable, we apply narrowings + // to the constraint type. + const parent = node.parent; + return parent.kind === SyntaxKind.PropertyAccessExpression || + parent.kind === SyntaxKind.CallExpression && (parent).expression === node || + parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === node; + } + + function getDeclaredOrApparentType(symbol: Symbol, node: Node) { + const type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && maybeTypeOfKind(type, TypeFlags.TypeVariable)) { + const apparentType = mapType(getWidenedType(type), getApparentType); + if (apparentType !== emptyObjectType) { + return apparentType; + } + } + return type; + } + function checkIdentifier(node: Identifier): Type { const symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -11783,7 +11807,7 @@ namespace ts { checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - const type = getTypeOfSymbol(localOrExportSymbol); + const type = getDeclaredOrApparentType(localOrExportSymbol, node); const declaration = localOrExportSymbol.valueDeclaration; const assignmentKind = getAssignmentTargetKind(node); @@ -14141,7 +14165,7 @@ namespace ts { checkPropertyAccessibility(node, left, apparentType, prop); - const propType = getTypeOfSymbol(prop); + const propType = getDeclaredOrApparentType(prop, node); const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind) { From 0c10098c66c5e0c757e5a10d04bff9e3a111a6b5 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 3 May 2017 15:28:08 -0700 Subject: [PATCH 065/282] Fix case of suggestion blacklist. It should be all lowercase since candidates have been lowercased by the point the blacklist is checked. --- src/compiler/checker.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c57e925e17e..d6c1f1f9776 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14227,14 +14227,14 @@ namespace ts { if (candidateName.length < 3 || name.length < 3 || candidateName === "eval" || - candidateName === "Intl" || + candidateName === "intl" || candidateName === "undefined" || - candidateName === "Map" || - candidateName === "NaN" || - candidateName === "Set") { + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { continue; } - const distance = levenshtein(candidateName, name); + const distance = levenshtein(name, candidateName); if (distance > worstDistance) { continue; } From 3d069f7a54bf3b1722882313e784a0b306ae1672 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 3 May 2017 21:28:03 -0700 Subject: [PATCH 066/282] New behavior only for type variables with nullable constraints --- src/compiler/checker.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9e24d6bb69e..3e5eddf3b05 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11711,10 +11711,6 @@ namespace ts { } function isApparentTypePosition(node: Node) { - // When a node is the left hand expression of a property access or call expression, the node occurs - // in an apparent type position. In such a position we fetch the apparent type of the node *before* - // performing control flow analysis such that, if the node is a type variable, we apply narrowings - // to the constraint type. const parent = node.parent; return parent.kind === SyntaxKind.PropertyAccessExpression || parent.kind === SyntaxKind.CallExpression && (parent).expression === node || @@ -11722,10 +11718,14 @@ namespace ts { } function getDeclaredOrApparentType(symbol: Symbol, node: Node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. const type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && maybeTypeOfKind(type, TypeFlags.TypeVariable)) { const apparentType = mapType(getWidenedType(type), getApparentType); - if (apparentType !== emptyObjectType) { + if (maybeTypeOfKind(apparentType, TypeFlags.Nullable)) { return apparentType; } } From 238067eb3befc5b6983055dcef240cdfabf4c742 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 3 May 2017 21:28:17 -0700 Subject: [PATCH 067/282] Add tests --- .../reference/typeVariableTypeGuards.js | 147 ++++++++++++ .../reference/typeVariableTypeGuards.symbols | 202 +++++++++++++++++ .../reference/typeVariableTypeGuards.types | 212 ++++++++++++++++++ .../cases/compiler/typeVariableTypeGuards.ts | 77 +++++++ 4 files changed, 638 insertions(+) create mode 100644 tests/baselines/reference/typeVariableTypeGuards.js create mode 100644 tests/baselines/reference/typeVariableTypeGuards.symbols create mode 100644 tests/baselines/reference/typeVariableTypeGuards.types create mode 100644 tests/cases/compiler/typeVariableTypeGuards.ts diff --git a/tests/baselines/reference/typeVariableTypeGuards.js b/tests/baselines/reference/typeVariableTypeGuards.js new file mode 100644 index 00000000000..c1337561b32 --- /dev/null +++ b/tests/baselines/reference/typeVariableTypeGuards.js @@ -0,0 +1,147 @@ +//// [typeVariableTypeGuards.ts] +// Repro from #14091 + +interface Foo { + foo(): void +} + +class A

> { + props: Readonly

+ doSomething() { + this.props.foo && this.props.foo() + } +} + +// Repro from #14415 + +interface Banana { + color: 'yellow'; +} + +class Monkey { + a: T; + render() { + if (this.a) { + this.a.color; + } + } +} + +interface BigBanana extends Banana { +} + +class BigMonkey extends Monkey { + render() { + if (this.a) { + this.a.color; + } + } +} + +// Another repro + +type Item = { + (): string; + x: string; +} + +function f1(obj: T) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f2(obj: T | undefined) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f3(obj: T | null) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f4(obj: T | undefined, x: number) { + if (obj) { + obj[x].length; + } +} + + +//// [typeVariableTypeGuards.js] +"use strict"; +// Repro from #14091 +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var A = (function () { + function A() { + } + A.prototype.doSomething = function () { + this.props.foo && this.props.foo(); + }; + return A; +}()); +var Monkey = (function () { + function Monkey() { + } + Monkey.prototype.render = function () { + if (this.a) { + this.a.color; + } + }; + return Monkey; +}()); +var BigMonkey = (function (_super) { + __extends(BigMonkey, _super); + function BigMonkey() { + return _super !== null && _super.apply(this, arguments) || this; + } + BigMonkey.prototype.render = function () { + if (this.a) { + this.a.color; + } + }; + return BigMonkey; +}(Monkey)); +function f1(obj) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} +function f2(obj) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} +function f3(obj) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} +function f4(obj, x) { + if (obj) { + obj[x].length; + } +} diff --git a/tests/baselines/reference/typeVariableTypeGuards.symbols b/tests/baselines/reference/typeVariableTypeGuards.symbols new file mode 100644 index 00000000000..e0c21e12adb --- /dev/null +++ b/tests/baselines/reference/typeVariableTypeGuards.symbols @@ -0,0 +1,202 @@ +=== tests/cases/compiler/typeVariableTypeGuards.ts === +// Repro from #14091 + +interface Foo { +>Foo : Symbol(Foo, Decl(typeVariableTypeGuards.ts, 0, 0)) + + foo(): void +>foo : Symbol(Foo.foo, Decl(typeVariableTypeGuards.ts, 2, 15)) +} + +class A

> { +>A : Symbol(A, Decl(typeVariableTypeGuards.ts, 4, 1)) +>P : Symbol(P, Decl(typeVariableTypeGuards.ts, 6, 8)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Foo : Symbol(Foo, Decl(typeVariableTypeGuards.ts, 0, 0)) + + props: Readonly

+>props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>P : Symbol(P, Decl(typeVariableTypeGuards.ts, 6, 8)) + + doSomething() { +>doSomething : Symbol(A.doSomething, Decl(typeVariableTypeGuards.ts, 7, 22)) + + this.props.foo && this.props.foo() +>this.props.foo : Symbol(foo) +>this.props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>this : Symbol(A, Decl(typeVariableTypeGuards.ts, 4, 1)) +>props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>foo : Symbol(foo) +>this.props.foo : Symbol(foo) +>this.props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>this : Symbol(A, Decl(typeVariableTypeGuards.ts, 4, 1)) +>props : Symbol(A.props, Decl(typeVariableTypeGuards.ts, 6, 33)) +>foo : Symbol(foo) + } +} + +// Repro from #14415 + +interface Banana { +>Banana : Symbol(Banana, Decl(typeVariableTypeGuards.ts, 11, 1)) + + color: 'yellow'; +>color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) +} + +class Monkey { +>Monkey : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 19, 13)) +>Banana : Symbol(Banana, Decl(typeVariableTypeGuards.ts, 11, 1)) + + a: T; +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 19, 13)) + + render() { +>render : Symbol(Monkey.render, Decl(typeVariableTypeGuards.ts, 20, 9)) + + if (this.a) { +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) + + this.a.color; +>this.a.color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) + } + } +} + +interface BigBanana extends Banana { +>BigBanana : Symbol(BigBanana, Decl(typeVariableTypeGuards.ts, 26, 1)) +>Banana : Symbol(Banana, Decl(typeVariableTypeGuards.ts, 11, 1)) +} + +class BigMonkey extends Monkey { +>BigMonkey : Symbol(BigMonkey, Decl(typeVariableTypeGuards.ts, 29, 1)) +>Monkey : Symbol(Monkey, Decl(typeVariableTypeGuards.ts, 17, 1)) +>BigBanana : Symbol(BigBanana, Decl(typeVariableTypeGuards.ts, 26, 1)) + + render() { +>render : Symbol(BigMonkey.render, Decl(typeVariableTypeGuards.ts, 31, 43)) + + if (this.a) { +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(BigMonkey, Decl(typeVariableTypeGuards.ts, 29, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) + + this.a.color; +>this.a.color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) +>this.a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>this : Symbol(BigMonkey, Decl(typeVariableTypeGuards.ts, 29, 1)) +>a : Symbol(Monkey.a, Decl(typeVariableTypeGuards.ts, 19, 44)) +>color : Symbol(Banana.color, Decl(typeVariableTypeGuards.ts, 15, 18)) + } + } +} + +// Another repro + +type Item = { +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) + + (): string; + x: string; +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +} + +function f1(obj: T) { +>f1 : Symbol(f1, Decl(typeVariableTypeGuards.ts, 44, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 46, 12)) +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 46, 12)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) + + obj.x; +>obj.x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj["x"]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) +>"x" : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj(); +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 46, 40)) + } +} + +function f2(obj: T | undefined) { +>f2 : Symbol(f2, Decl(typeVariableTypeGuards.ts, 52, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 54, 12)) +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 54, 12)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) + + obj.x; +>obj.x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj["x"]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) +>"x" : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj(); +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 54, 40)) + } +} + +function f3(obj: T | null) { +>f3 : Symbol(f3, Decl(typeVariableTypeGuards.ts, 60, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 62, 12)) +>Item : Symbol(Item, Decl(typeVariableTypeGuards.ts, 37, 1)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 62, 12)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) + + obj.x; +>obj.x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj["x"]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) +>"x" : Symbol(x, Decl(typeVariableTypeGuards.ts, 42, 15)) + + obj(); +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 62, 40)) + } +} + +function f4(obj: T | undefined, x: number) { +>f4 : Symbol(f4, Decl(typeVariableTypeGuards.ts, 68, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 70, 12)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 70, 44)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 70, 12)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 70, 63)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 70, 44)) + + obj[x].length; +>obj[x].length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 70, 44)) +>x : Symbol(x, Decl(typeVariableTypeGuards.ts, 70, 63)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + } +} + diff --git a/tests/baselines/reference/typeVariableTypeGuards.types b/tests/baselines/reference/typeVariableTypeGuards.types new file mode 100644 index 00000000000..a20129440a0 --- /dev/null +++ b/tests/baselines/reference/typeVariableTypeGuards.types @@ -0,0 +1,212 @@ +=== tests/cases/compiler/typeVariableTypeGuards.ts === +// Repro from #14091 + +interface Foo { +>Foo : Foo + + foo(): void +>foo : () => void +} + +class A

> { +>A : A

+>P : P +>Partial : Partial +>Foo : Foo + + props: Readonly

+>props : Readonly

+>Readonly : Readonly +>P : P + + doSomething() { +>doSomething : () => void + + this.props.foo && this.props.foo() +>this.props.foo && this.props.foo() : void +>this.props.foo : P["foo"] +>this.props : Readonly

+>this : this +>props : Readonly

+>foo : P["foo"] +>this.props.foo() : void +>this.props.foo : () => void +>this.props : Readonly

+>this : this +>props : Readonly

+>foo : () => void + } +} + +// Repro from #14415 + +interface Banana { +>Banana : Banana + + color: 'yellow'; +>color : "yellow" +} + +class Monkey { +>Monkey : Monkey +>T : T +>Banana : Banana + + a: T; +>a : T +>T : T + + render() { +>render : () => void + + if (this.a) { +>this.a : T +>this : this +>a : T + + this.a.color; +>this.a.color : "yellow" +>this.a : Banana +>this : this +>a : Banana +>color : "yellow" + } + } +} + +interface BigBanana extends Banana { +>BigBanana : BigBanana +>Banana : Banana +} + +class BigMonkey extends Monkey { +>BigMonkey : BigMonkey +>Monkey : Monkey +>BigBanana : BigBanana + + render() { +>render : () => void + + if (this.a) { +>this.a : BigBanana +>this : this +>a : BigBanana + + this.a.color; +>this.a.color : "yellow" +>this.a : BigBanana +>this : this +>a : BigBanana +>color : "yellow" + } + } +} + +// Another repro + +type Item = { +>Item : Item + + (): string; + x: string; +>x : string +} + +function f1(obj: T) { +>f1 : (obj: T) => void +>T : T +>Item : Item +>obj : T +>T : T + + if (obj) { +>obj : T + + obj.x; +>obj.x : string +>obj : Item +>x : string + + obj["x"]; +>obj["x"] : string +>obj : Item +>"x" : "x" + + obj(); +>obj() : string +>obj : Item + } +} + +function f2(obj: T | undefined) { +>f2 : (obj: T | undefined) => void +>T : T +>Item : Item +>obj : T | undefined +>T : T + + if (obj) { +>obj : T | undefined + + obj.x; +>obj.x : string +>obj : Item +>x : string + + obj["x"]; +>obj["x"] : string +>obj : Item +>"x" : "x" + + obj(); +>obj() : string +>obj : Item + } +} + +function f3(obj: T | null) { +>f3 : (obj: T | null) => void +>T : T +>Item : Item +>obj : T | null +>T : T +>null : null + + if (obj) { +>obj : T | null + + obj.x; +>obj.x : string +>obj : Item +>x : string + + obj["x"]; +>obj["x"] : string +>obj : Item +>"x" : "x" + + obj(); +>obj() : string +>obj : Item + } +} + +function f4(obj: T | undefined, x: number) { +>f4 : (obj: T | undefined, x: number) => void +>T : T +>obj : T | undefined +>T : T +>x : number + + if (obj) { +>obj : T | undefined + + obj[x].length; +>obj[x].length : number +>obj[x] : string +>obj : string[] +>x : number +>length : number + } +} + diff --git a/tests/cases/compiler/typeVariableTypeGuards.ts b/tests/cases/compiler/typeVariableTypeGuards.ts new file mode 100644 index 00000000000..a962fd786c7 --- /dev/null +++ b/tests/cases/compiler/typeVariableTypeGuards.ts @@ -0,0 +1,77 @@ +// @strict: true + +// Repro from #14091 + +interface Foo { + foo(): void +} + +class A

> { + props: Readonly

+ doSomething() { + this.props.foo && this.props.foo() + } +} + +// Repro from #14415 + +interface Banana { + color: 'yellow'; +} + +class Monkey { + a: T; + render() { + if (this.a) { + this.a.color; + } + } +} + +interface BigBanana extends Banana { +} + +class BigMonkey extends Monkey { + render() { + if (this.a) { + this.a.color; + } + } +} + +// Another repro + +type Item = { + (): string; + x: string; +} + +function f1(obj: T) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f2(obj: T | undefined) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f3(obj: T | null) { + if (obj) { + obj.x; + obj["x"]; + obj(); + } +} + +function f4(obj: T | undefined, x: number) { + if (obj) { + obj[x].length; + } +} From 8d8c4c2990e5611f78d1c52ece73ca8db7af6e49 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 4 May 2017 08:42:56 -0700 Subject: [PATCH 068/282] Reuse code from getTypeReferenceType --- src/compiler/checker.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 61503415d81..ec5c0d38532 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6687,11 +6687,7 @@ namespace ts { ? (node).expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; - const typeArguments = typeArgumentsFromTypeReferenceNode(node); - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol, typeArguments) : - symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol, typeArguments) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. From 49fd1ad80b19aa2ef1110d6f5255ba4fe4efd15f Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 4 May 2017 10:11:25 -0700 Subject: [PATCH 069/282] Add JS declaration to index constraint check error reporting Now Javascript-style declarations like `this.foo = "bar"` are handled correctly. --- src/compiler/checker.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e1ed2f4fa1f..9649a4b3bdc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -20233,7 +20233,10 @@ namespace ts { // perform property check if property or indexer is declared in 'type' // this allows to rule out cases when both property and indexer are inherited from the base class let errorNode: Node; - if (propDeclaration && (propDeclaration.name.kind === SyntaxKind.ComputedPropertyName || prop.parent === containingType.symbol)) { + if (propDeclaration && + (getSpecialPropertyAssignmentKind(propDeclaration as BinaryExpression) === SpecialPropertyAssignmentKind.ThisProperty || + propDeclaration.name.kind === SyntaxKind.ComputedPropertyName || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { From 3e85ac062716c06cccd2e9f70a8c8d0e66d1f020 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 4 May 2017 10:12:49 -0700 Subject: [PATCH 070/282] Test:index constraint check on js class expression --- ...exConstraintOfJavascriptClassExpression.js | 32 +++++++++++++++++++ ...straintOfJavascriptClassExpression.symbols | 17 ++++++++++ ...onstraintOfJavascriptClassExpression.types | 22 +++++++++++++ ...exConstraintOfJavascriptClassExpression.ts | 10 ++++++ 4 files changed, 81 insertions(+) create mode 100644 tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js create mode 100644 tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols create mode 100644 tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types create mode 100644 tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js new file mode 100644 index 00000000000..a23461a1b58 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js @@ -0,0 +1,32 @@ +//// [weird.js] +someFunction(function(BaseClass) { + class Hello extends BaseClass { + constructor() { + this.foo = "bar"; + } + } +}); + + +//// [foo.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +someFunction(function (BaseClass) { + var Hello = (function (_super) { + __extends(Hello, _super); + function Hello() { + var _this = this; + _this.foo = "bar"; + return _this; + } + return Hello; + }(BaseClass)); +}); diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols new file mode 100644 index 00000000000..c9ee830a9a5 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/weird.js === +someFunction(function(BaseClass) { +>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22)) + + class Hello extends BaseClass { +>Hello : Symbol(Hello, Decl(weird.js, 0, 34)) +>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22)) + + constructor() { + this.foo = "bar"; +>this.foo : Symbol(Hello.foo, Decl(weird.js, 2, 17)) +>this : Symbol(Hello, Decl(weird.js, 0, 34)) +>foo : Symbol(Hello.foo, Decl(weird.js, 2, 17)) + } + } +}); + diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types new file mode 100644 index 00000000000..6a0a5ad1479 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/weird.js === +someFunction(function(BaseClass) { +>someFunction(function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }}) : any +>someFunction : any +>function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }} : (BaseClass: any) => void +>BaseClass : any + + class Hello extends BaseClass { +>Hello : Hello +>BaseClass : any + + constructor() { + this.foo = "bar"; +>this.foo = "bar" : "bar" +>this.foo : string +>this : this +>foo : string +>"bar" : "bar" + } + } +}); + diff --git a/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts new file mode 100644 index 00000000000..8de18a69536 --- /dev/null +++ b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts @@ -0,0 +1,10 @@ +// @Filename: weird.js +// @allowJs: true +// @out: foo.js +someFunction(function(BaseClass) { + class Hello extends BaseClass { + constructor() { + this.foo = "bar"; + } + } +}); From 4123068f19e293076ad2064998886a484535ec73 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 4 May 2017 10:20:04 -0700 Subject: [PATCH 071/282] Only get apparent type when constraint includes nullable types --- src/compiler/checker.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3e5eddf3b05..2261e0f1a92 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11717,17 +11717,18 @@ namespace ts { parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === node; } + function typeHasNullableConstraint(type: Type) { + return type.flags & TypeFlags.TypeVariable && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, TypeFlags.Nullable); + } + function getDeclaredOrApparentType(symbol: Symbol, node: Node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. const type = getTypeOfSymbol(symbol); - if (isApparentTypePosition(node) && maybeTypeOfKind(type, TypeFlags.TypeVariable)) { - const apparentType = mapType(getWidenedType(type), getApparentType); - if (maybeTypeOfKind(apparentType, TypeFlags.Nullable)) { - return apparentType; - } + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); } return type; } From a6dfd66fc1603165b35a7ffac6695de526caafb0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 4 May 2017 10:20:13 -0700 Subject: [PATCH 072/282] Update tests --- .../reference/typeVariableTypeGuards.js | 11 ++++++++++ .../reference/typeVariableTypeGuards.symbols | 19 ++++++++++++++++++ .../reference/typeVariableTypeGuards.types | 20 +++++++++++++++++++ .../cases/compiler/typeVariableTypeGuards.ts | 6 ++++++ 4 files changed, 56 insertions(+) diff --git a/tests/baselines/reference/typeVariableTypeGuards.js b/tests/baselines/reference/typeVariableTypeGuards.js index c1337561b32..8525bde0f77 100644 --- a/tests/baselines/reference/typeVariableTypeGuards.js +++ b/tests/baselines/reference/typeVariableTypeGuards.js @@ -74,6 +74,12 @@ function f4(obj: T | undefined, x: number) { obj[x].length; } } + +function f5(obj: T | undefined, key: K) { + if (obj) { + obj[key]; + } +} //// [typeVariableTypeGuards.js] @@ -145,3 +151,8 @@ function f4(obj, x) { obj[x].length; } } +function f5(obj, key) { + if (obj) { + obj[key]; + } +} diff --git a/tests/baselines/reference/typeVariableTypeGuards.symbols b/tests/baselines/reference/typeVariableTypeGuards.symbols index e0c21e12adb..fa94cfd9462 100644 --- a/tests/baselines/reference/typeVariableTypeGuards.symbols +++ b/tests/baselines/reference/typeVariableTypeGuards.symbols @@ -200,3 +200,22 @@ function f4(obj: T | undefined, x: number) { } } +function f5(obj: T | undefined, key: K) { +>f5 : Symbol(f5, Decl(typeVariableTypeGuards.ts, 74, 1)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 76, 12)) +>K : Symbol(K, Decl(typeVariableTypeGuards.ts, 76, 14)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 76, 12)) +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 76, 34)) +>T : Symbol(T, Decl(typeVariableTypeGuards.ts, 76, 12)) +>key : Symbol(key, Decl(typeVariableTypeGuards.ts, 76, 53)) +>K : Symbol(K, Decl(typeVariableTypeGuards.ts, 76, 14)) + + if (obj) { +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 76, 34)) + + obj[key]; +>obj : Symbol(obj, Decl(typeVariableTypeGuards.ts, 76, 34)) +>key : Symbol(key, Decl(typeVariableTypeGuards.ts, 76, 53)) + } +} + diff --git a/tests/baselines/reference/typeVariableTypeGuards.types b/tests/baselines/reference/typeVariableTypeGuards.types index a20129440a0..bfcf851648a 100644 --- a/tests/baselines/reference/typeVariableTypeGuards.types +++ b/tests/baselines/reference/typeVariableTypeGuards.types @@ -210,3 +210,23 @@ function f4(obj: T | undefined, x: number) { } } +function f5(obj: T | undefined, key: K) { +>f5 : (obj: T | undefined, key: K) => void +>T : T +>K : K +>T : T +>obj : T | undefined +>T : T +>key : K +>K : K + + if (obj) { +>obj : T | undefined + + obj[key]; +>obj[key] : T[K] +>obj : T +>key : K + } +} + diff --git a/tests/cases/compiler/typeVariableTypeGuards.ts b/tests/cases/compiler/typeVariableTypeGuards.ts index a962fd786c7..0a4221c93a0 100644 --- a/tests/cases/compiler/typeVariableTypeGuards.ts +++ b/tests/cases/compiler/typeVariableTypeGuards.ts @@ -75,3 +75,9 @@ function f4(obj: T | undefined, x: number) { obj[x].length; } } + +function f5(obj: T | undefined, key: K) { + if (obj) { + obj[key]; + } +} From 398d3aaf6cae5026416550608e9adb4fcdaa01ab Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 4 May 2017 12:45:15 -0700 Subject: [PATCH 073/282] Symbol table for homomorphic mapped type: Don't needlessly create twice --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e1ed2f4fa1f..ec88d88c3ad 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10022,7 +10022,7 @@ namespace ts { const templateType = getTemplateTypeFromMappedType(target); const readonlyMask = target.declaration.readonlyToken ? false : true; const optionalMask = target.declaration.questionToken ? 0 : SymbolFlags.Optional; - const members = createSymbolTable(properties); + const members = createMap(); for (const prop of properties) { const inferredPropType = inferTargetType(getTypeOfSymbol(prop)); if (!inferredPropType) { From cbeb11eabf17895e182917d689454aa47d76fd86 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Thu, 4 May 2017 13:09:35 -0700 Subject: [PATCH 074/282] Add check for tslib __await helper --- src/compiler/checker.ts | 54 +++++++++++-------- src/compiler/transformers/esnext.ts | 2 +- src/compiler/types.ts | 15 ++++-- src/compiler/utilities.ts | 18 ++++--- ...persNoHelpersForAsyncGenerators.errors.txt | 27 ++++++++++ ...mportHelpersNoHelpersForAsyncGenerators.js | 37 +++++++++++++ ...mportHelpersNoHelpersForAsyncGenerators.ts | 16 ++++++ 7 files changed, 134 insertions(+), 35 deletions(-) create mode 100644 tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.errors.txt create mode 100644 tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.js create mode 100644 tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 34a176ac23c..041e0ea9989 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15987,7 +15987,7 @@ namespace ts { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async + return (functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -16203,7 +16203,7 @@ namespace ts { const functionFlags = getFunctionFlags(node); const returnOrPromisedType = node.type && - ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async ? + ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function @@ -16233,7 +16233,7 @@ namespace ts { // its return type annotation. const exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async) { // Async function + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { // Async function const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -16973,12 +16973,16 @@ namespace ts { // we are in a yield context. const functionFlags = func && getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & FunctionFlags.Async) { - if (languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncDelegator); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && + languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncDelegatorIncludes); } - else if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { + + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Generator && + languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Values); } } @@ -17497,18 +17501,20 @@ namespace ts { } const functionFlags = getFunctionFlags(node); - if ((functionFlags & FunctionFlags.InvalidAsyncOrAsyncGenerator) === FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter); - if (languageVersion < ScriptTarget.ES2015) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator); + if (!(functionFlags & FunctionFlags.Invalid)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncGeneratorIncludes); } - } - if ((functionFlags & FunctionFlags.InvalidGenerator) === FunctionFlags.Generator) { - if (functionFlags & FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncGenerator); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter); } - else if (languageVersion < ScriptTarget.ES2015) { + + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & FunctionFlags.AsyncGenerator) !== FunctionFlags.Normal && languageVersion < ScriptTarget.ES2015) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator); } } @@ -17536,7 +17542,7 @@ namespace ts { if (node.type) { const functionFlags = getFunctionFlags(node); - if ((functionFlags & FunctionFlags.InvalidGenerator) === FunctionFlags.Generator) { + if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Generator)) === FunctionFlags.Generator) { const returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -17556,7 +17562,7 @@ namespace ts { checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async) { + else if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { checkAsyncFunctionReturnType(node); } } @@ -19523,11 +19529,14 @@ namespace ts { if (node.kind === SyntaxKind.ForOfStatement) { if ((node).awaitModifier) { - if (languageVersion < ScriptTarget.ES2017) { + const functionFlags = getFunctionFlags(getContainingFunction(node)); + if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Async)) === FunctionFlags.Async && languageVersion < ScriptTarget.ESNext) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper checkExternalEmitHelpers(node, ExternalEmitHelpers.ForAwaitOfIncludes); } } - else if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < ScriptTarget.ES2015) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, ExternalEmitHelpers.ForOfIncludes); } } @@ -19957,7 +19966,7 @@ namespace ts { } function isUnwrappedReturnTypeVoidOrAny(func: FunctionLikeDeclaration, returnType: Type): boolean { - const unwrappedReturnType = (getFunctionFlags(func) & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async + const unwrappedReturnType = (getFunctionFlags(func) & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, TypeFlags.Void | TypeFlags.Any); @@ -22964,6 +22973,7 @@ namespace ts { case ExternalEmitHelpers.Values: return "__values"; case ExternalEmitHelpers.Read: return "__read"; case ExternalEmitHelpers.Spread: return "__spread"; + case ExternalEmitHelpers.Await: return "__await"; case ExternalEmitHelpers.AsyncGenerator: return "__asyncGenerator"; case ExternalEmitHelpers.AsyncDelegator: return "__asyncDelegator"; case ExternalEmitHelpers.AsyncValues: return "__asyncValues"; diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 8d88d9b286b..fef1b009ba3 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -884,7 +884,7 @@ namespace ts { function createAwaitHelper(context: TransformationContext, expression: Expression) { context.requestEmitHelper(awaitHelper); - return createCall(createIdentifier("__await"), /*typeArguments*/ undefined, [expression]); + return createCall(getHelperName("__await"), /*typeArguments*/ undefined, [expression]); } const asyncGeneratorHelper: EmitHelper = { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 57cf17f7100..ad3e181610a 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3973,11 +3973,12 @@ namespace ts { Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) Generator = 1 << 7, // __generator (used by ES2015 generator transformation) Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations) - Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) + Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) Spread = 1 << 10, // __spread (used by ES2015 array spread and argument list spread transformations) - AsyncGenerator = 1 << 11, // __asyncGenerator (used by ES2017 async generator transformation) - AsyncDelegator = 1 << 12, // __asyncDelegator (used by ES2017 async generator yield* transformation) - AsyncValues = 1 << 13, // __asyncValues (used by ES2017 for..await..of transformation) + Await = 1 << 11, // __await (used by ES2017 async generator transformation) + AsyncGenerator = 1 << 12, // __asyncGenerator (used by ES2017 async generator transformation) + AsyncDelegator = 1 << 13, // __asyncDelegator (used by ES2017 async generator yield* transformation) + AsyncValues = 1 << 14, // __asyncValues (used by ES2017 for..await..of transformation) // Helpers included by ES2015 for..of ForOfIncludes = Values, @@ -3985,6 +3986,12 @@ namespace ts { // Helpers included by ES2017 for..await..of ForAwaitOfIncludes = AsyncValues, + // Helpers included by ES2017 async generators + AsyncGeneratorIncludes = Await | AsyncGenerator, + + // Helpers included by yield* in ES2017 async generators + AsyncDelegatorIncludes = Await | AsyncDelegator | AsyncValues, + // Helpers included by ES2015 spread SpreadIncludes = Read | Spread, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 646a7b22e3f..0723a1fc74f 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1925,16 +1925,18 @@ namespace ts { } export const enum FunctionFlags { - Normal = 0, - Generator = 1 << 0, - Async = 1 << 1, - AsyncOrAsyncGenerator = Async | Generator, - Invalid = 1 << 2, - InvalidAsyncOrAsyncGenerator = AsyncOrAsyncGenerator | Invalid, - InvalidGenerator = Generator | Invalid, + Normal = 0, // Function is a normal function + Generator = 1 << 0, // Function is a generator function or async generator function + Async = 1 << 1, // Function is an async function or an async generator function + Invalid = 1 << 2, // Function is a signature or overload and does not have a body. + AsyncGenerator = Async | Generator, // Function is an async generator function } - export function getFunctionFlags(node: FunctionLikeDeclaration) { + export function getFunctionFlags(node: FunctionLikeDeclaration | undefined) { + if (!node) { + return FunctionFlags.Invalid; + } + let flags = FunctionFlags.Normal; switch (node.kind) { case SyntaxKind.FunctionDeclaration: diff --git a/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.errors.txt b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.errors.txt new file mode 100644 index 00000000000..633b812c356 --- /dev/null +++ b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.errors.txt @@ -0,0 +1,27 @@ +tests/cases/compiler/main.ts(1,25): error TS2343: This syntax requires an imported helper named '__asyncGenerator', but module 'tslib' has no exported member '__asyncGenerator'. +tests/cases/compiler/main.ts(1,25): error TS2343: This syntax requires an imported helper named '__await', but module 'tslib' has no exported member '__await'. +tests/cases/compiler/main.ts(1,25): error TS2343: This syntax requires an imported helper named '__generator', but module 'tslib' has no exported member '__generator'. +tests/cases/compiler/main.ts(4,5): error TS2343: This syntax requires an imported helper named '__asyncDelegator', but module 'tslib' has no exported member '__asyncDelegator'. +tests/cases/compiler/main.ts(4,5): error TS2343: This syntax requires an imported helper named '__asyncValues', but module 'tslib' has no exported member '__asyncValues'. + + +==== tests/cases/compiler/main.ts (5 errors) ==== + export async function * f() { + ~ +!!! error TS2343: This syntax requires an imported helper named '__asyncGenerator', but module 'tslib' has no exported member '__asyncGenerator'. + ~ +!!! error TS2343: This syntax requires an imported helper named '__await', but module 'tslib' has no exported member '__await'. + ~ +!!! error TS2343: This syntax requires an imported helper named '__generator', but module 'tslib' has no exported member '__generator'. + await 1; + yield 2; + yield* [3]; + ~~~~~~~~~~ +!!! error TS2343: This syntax requires an imported helper named '__asyncDelegator', but module 'tslib' has no exported member '__asyncDelegator'. + ~~~~~~~~~~ +!!! error TS2343: This syntax requires an imported helper named '__asyncValues', but module 'tslib' has no exported member '__asyncValues'. + } + +==== tests/cases/compiler/tslib.d.ts (0 errors) ==== + export {} + \ No newline at end of file diff --git a/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.js b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.js new file mode 100644 index 00000000000..699c4faf921 --- /dev/null +++ b/tests/baselines/reference/importHelpersNoHelpersForAsyncGenerators.js @@ -0,0 +1,37 @@ +//// [tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts] //// + +//// [main.ts] +export async function * f() { + await 1; + yield 2; + yield* [3]; +} + +//// [tslib.d.ts] +export {} + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = require("tslib"); +function f() { + return tslib_1.__asyncGenerator(this, arguments, function f_1() { + return tslib_1.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tslib_1.__await(1)]; + case 1: + _a.sent(); + return [4 /*yield*/, 2]; + case 2: + _a.sent(); + return [5 /*yield**/, tslib_1.__values(tslib_1.__asyncDelegator(tslib_1.__asyncValues([3])))]; + case 3: return [4 /*yield*/, tslib_1.__await.apply(void 0, [_a.sent()])]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); +} +exports.f = f; diff --git a/tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts b/tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts new file mode 100644 index 00000000000..a42b5148b43 --- /dev/null +++ b/tests/cases/compiler/importHelpersNoHelpersForAsyncGenerators.ts @@ -0,0 +1,16 @@ +// @importHelpers: true +// @target: es5 +// @module: commonjs +// @lib: esnext +// @moduleResolution: classic +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @filename: main.ts +export async function * f() { + await 1; + yield 2; + yield* [3]; +} + +// @filename: tslib.d.ts +export {} From 6f357e5a6ca28eb394bf229b6e1bd67f4a41b65d Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Thu, 4 May 2017 13:33:28 -0700 Subject: [PATCH 075/282] Update baselines --- ...mitter.asyncGenerators.classMethods.es5.js | 42 +++++++++---------- ...syncGenerators.functionDeclarations.es5.js | 42 +++++++++---------- ...asyncGenerators.functionExpressions.es5.js | 42 +++++++++---------- ...syncGenerators.objectLiteralMethods.es5.js | 42 +++++++++---------- 4 files changed, 76 insertions(+), 92 deletions(-) diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js index 4d78db84c03..1fa1b19e36f 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js @@ -293,15 +293,13 @@ var C4 = (function () { } C4.prototype.f = function () { return __asyncGenerator(this, arguments, function f_1() { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); @@ -374,22 +372,20 @@ var C5 = (function () { } C5.prototype.f = function () { return __asyncGenerator(this, arguments, function f_1() { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, 1]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })())))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js index c5b09b216d5..f842a2c813a 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js @@ -244,15 +244,13 @@ var __values = (this && this.__values) || function (o) { }; function f4() { return __asyncGenerator(this, arguments, function f4_1() { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); @@ -320,22 +318,20 @@ var __values = (this && this.__values) || function (o) { }; function f5() { return __asyncGenerator(this, arguments, function f5_1() { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, 1]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })())))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js index 7a40ba1808f..779d9c5340e 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js @@ -244,15 +244,13 @@ var __values = (this && this.__values) || function (o) { }; var f4 = function () { return __asyncGenerator(this, arguments, function () { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); @@ -320,22 +318,20 @@ var __values = (this && this.__values) || function (o) { }; var f5 = function () { return __asyncGenerator(this, arguments, function () { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, 1]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })())))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js index a76028b028e..46f3a1efac2 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js @@ -265,15 +265,13 @@ var __values = (this && this.__values) || function (o) { var o4 = { f: function () { return __asyncGenerator(this, arguments, function f_1() { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues([1])))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); @@ -343,22 +341,20 @@ var __values = (this && this.__values) || function (o) { var o5 = { f: function () { return __asyncGenerator(this, arguments, function f_1() { - var x, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = __await; - return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, 1]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); }); })())))]; - case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])]; + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues((function () { return __asyncGenerator(this, arguments, function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); }); })())))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; case 2: - x = _b.sent(); + x = _a.sent(); return [2 /*return*/]; } }); From 7dddcb816f05875197aaf3f7ff60578020526948 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 4 May 2017 14:16:09 -0700 Subject: [PATCH 076/282] Deduplicate jsDocTagNames and sort alphabetically --- src/services/jsDoc.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 37c22b4352c..4422aab7156 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -28,6 +28,7 @@ namespace ts.JsDoc { "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -38,8 +39,6 @@ namespace ts.JsDoc { "throws", "type", "typedef", - "property", - "prop", "version" ]; let jsDocTagNameCompletionEntries: CompletionEntry[]; From 705774e70797009950047d4102f80be9ae2efb44 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 4 May 2017 14:38:06 -0700 Subject: [PATCH 077/282] Remove tests that depended on exact number of jsdoc tag names --- tests/cases/fourslash/completionInJsDoc.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tests/cases/fourslash/completionInJsDoc.ts b/tests/cases/fourslash/completionInJsDoc.ts index 60707905956..4c1bb004671 100644 --- a/tests/cases/fourslash/completionInJsDoc.ts +++ b/tests/cases/fourslash/completionInJsDoc.ts @@ -84,23 +84,18 @@ goTo.marker('8'); verify.completionListContains('number'); goTo.marker('9'); -verify.completionListCount(40); verify.completionListContains("@argument"); goTo.marker('10'); -verify.completionListCount(40); verify.completionListContains("@returns"); goTo.marker('11'); -verify.completionListCount(40); verify.completionListContains("@argument"); goTo.marker('12'); -verify.completionListCount(40); verify.completionListContains("@constructor"); goTo.marker('13'); -verify.completionListCount(40); verify.completionListContains("@param"); goTo.marker('14'); From ae06e122384a2d6870fed2b18da7f9b3fb5a5e23 Mon Sep 17 00:00:00 2001 From: Yui T Date: Thu, 4 May 2017 14:39:51 -0700 Subject: [PATCH 078/282] Wip-fixing spread type --- src/compiler/checker.ts | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e1ed2f4fa1f..c2e88424c42 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13249,6 +13249,8 @@ namespace ts { let spread: Type = emptyObjectType; let attributesArray: Symbol[] = []; let hasSpreadAnyType = false; + let explicitlySpecifyChildrenAttribute = false; + const jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; @@ -13267,6 +13269,9 @@ namespace ts { attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); @@ -13327,8 +13332,7 @@ namespace ts { // Error if there is a attribute named "children" and children element. // This is because children element will overwrite the value from attributes - const jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { if (attributesTable.has(jsxChildrenPropertyName)) { error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } @@ -13351,7 +13355,7 @@ namespace ts { */ function createJsxAttributesType(symbol: Symbol, attributesTable: Map) { const result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; + const freshObjectLiteralFlag = spread !== emptyObjectType || compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag; result.objectFlags |= ObjectFlags.ObjectLiteral; return result; @@ -13903,7 +13907,15 @@ namespace ts { error(openingLikeElement, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + const isAssignableToTargetAttributes = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // TODO (yuisu): comment + if (isAssignableToTargetAttributes && sourceAttributesType !== anyType && !(sourceAttributesType.flags & TypeFlags.FreshLiteral)) { + for (const attribute of openingLikeElement.attributes.properties) { + if (isJsxAttribute(attribute) && !getPropertyOfType(targetAttributesType, attribute.name.text)) { + error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + } + } + } } } From 384d54603f00db19d32045bca29645e6ca8aea4d Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 4 May 2017 15:27:50 -0700 Subject: [PATCH 079/282] Basic parens handling and stubbed TypeFormatFlags --- src/compiler/checker.ts | 74 +++++++++++++++++++++++++------ src/compiler/emitter.ts | 3 +- src/compiler/factory.ts | 12 +++++ src/compiler/types.ts | 38 ++++++++++++---- src/compiler/visitor.ts | 3 +- src/services/codefixes/helpers.ts | 2 +- 6 files changed, 107 insertions(+), 25 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 91eee774ee4..fc067d63d59 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2287,8 +2287,16 @@ namespace ts { interface NodeBuilderContext { readonly enclosingDeclaration: Node | undefined; readonly flags: NodeBuilderFlags | undefined; + + // State encounteredError: boolean; inObjectTypeLiteral: boolean; + // TODO: needed for part of parens handling + InElementType: boolean; // Writing an array or union element type + // TODO: ??? + InFirstTypeArgument: boolean; // Writing first type argument of the instantiated type + // TODO: ??? + InTypeAlias: boolean; // Writing type in type alias declaration checkAlias: boolean; symbolStack: Symbol[] | undefined; } @@ -2299,18 +2307,28 @@ namespace ts { flags, encounteredError: false, inObjectTypeLiteral: false, + InElementType: false, + InFirstTypeArgument: false, + InTypeAlias: false, checkAlias: true, symbolStack: undefined }; } function typeToTypeNodeHelper(type: Type, context: NodeBuilderContext): TypeNode { + const InElementType = context.InElementType; + // TODO: why doesn't tts unset the flag? + context.InElementType = false; + + // TODO: should be assert? if (!type) { context.encounteredError = true; // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } + + if (type.flags & TypeFlags.Any) { return createKeywordTypeNode(SyntaxKind.AnyKeyword); } @@ -2390,16 +2408,17 @@ namespace ts { if (context.checkAlias && type.aliasSymbol) { const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, context); - const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, /*addInElementTypeFlag*/ false); return createTypeReferenceNode(name, typeArgumentNodes); } context.checkAlias = false; - if (type.flags & TypeFlags.Union) { - const formattedUnionTypes = formatUnionTypes((type).types); - const unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, unionTypeNodes); + if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { + const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; + const typeNodes = types && mapToTypeNodeArray(types, /*addInElementTypeFlag*/ true); + if (typeNodes && typeNodes.length > 0) { + const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); + return InElementType ? createParenthesizedTypeNode(unionOrIntersectionTypeNode) : unionOrIntersectionTypeNode; } else { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyUnionOrIntersection)) { @@ -2409,10 +2428,6 @@ namespace ts { } } - if (type.flags & TypeFlags.Intersection) { - return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, mapToTypeNodeArray((type as UnionType).types)); - } - if (objectFlags & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) { Debug.assert(!!(type.flags & TypeFlags.Object)); // The type is an object literal type. @@ -2421,25 +2436,33 @@ namespace ts { if (type.flags & TypeFlags.Index) { const indexedType = (type).type; + context.InElementType = true; const indexTypeNode = typeToTypeNodeHelper(indexedType, context); + Debug.assert(context.InElementType === false); return createTypeOperatorNode(indexTypeNode); } + if (type.flags & TypeFlags.IndexedAccess) { + context.InElementType = true; const objectTypeNode = typeToTypeNodeHelper((type).objectType, context); + Debug.assert(context.InElementType === false); const indexTypeNode = typeToTypeNodeHelper((type).indexType, context); return createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types: Type[]): TypeNode[] { + function mapToTypeNodeArray(types: Type[], addInElementTypeFlag: boolean): TypeNode[] { const result = []; + Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); for (const type of types) { + context.InElementType = addInElementTypeFlag; const typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); } } + Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); return result; } @@ -2523,6 +2546,7 @@ namespace ts { if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; + shouldAddParenthesisAroundFunctionType(signature, context); return signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { @@ -2538,6 +2562,20 @@ namespace ts { return createTypeLiteralNode(members); } + + function shouldAddParenthesisAroundFunctionType(callSignature: Signature, context: NodeBuilderContext) { + if (context.InElementType) { + return true; + } + else if (context.InFirstTypeArgument) { + // Add parenthesis around function type for the first type argument to avoid ambiguity + const typeParameters = callSignature.target && (context.flags & NodeBuilderFlags.WriteTypeArgumentsOfSignature) ? + callSignature.target.typeParameters : callSignature.typeParameters; + return typeParameters && typeParameters.length !== 0; + } + return false; + } + function createTypeQueryNodeFromSymbol(symbol: Symbol) { const entityName = symbolToName(symbol, /*expectsIdentifier*/ false, context); return createTypeQueryNode(entityName); @@ -2546,12 +2584,14 @@ namespace ts { function typeReferenceToTypeNode(type: TypeReference) { const typeArguments: Type[] = type.typeArguments || emptyArray; if (type.target === globalArrayType) { + context.InElementType = true; const elementType = typeToTypeNodeHelper(typeArguments[0], context); + context.InElementType = false; return createArrayTypeNode(elementType); } else if (type.target.objectFlags & ObjectFlags.Tuple) { if (typeArguments.length > 0) { - const tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + const tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type)), /*addInElementTypeFlag*/ false); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return createTupleTypeNode(tupleConstituentNodes); } @@ -2566,6 +2606,7 @@ namespace ts { let i = 0; let qualifiedName: QualifiedName | undefined = undefined; if (outerTypeParameters) { + let inFirstTypeArgument = true; const length = outerTypeParameters.length; while (i < length) { // Find group of type arguments for type parameters with the same declaring container. @@ -2577,6 +2618,7 @@ namespace ts { // 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 (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { + // inFirstTypeArgument??? const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true, context); if (!qualifiedName) { qualifiedName = createQualifiedName(qualifiedNamePart, /*right*/ undefined); @@ -2587,6 +2629,7 @@ namespace ts { qualifiedName = createQualifiedName(qualifiedName, /*right*/ undefined); } } + inFirstTypeArgument = false; } } let entityName: EntityName = undefined; @@ -2600,7 +2643,7 @@ namespace ts { entityName = nameIdentifier; } const typeParameterCount = (type.target.typeParameters || emptyArray).length; - const typeArgumentNodes = some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + const typeArgumentNodes = some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i), /*addInElementTypeFlag*/ false) : undefined; return createTypeReferenceNode(entityName, typeArgumentNodes); } } @@ -2695,7 +2738,7 @@ namespace ts { const returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if(context.flags & NodeBuilderFlags.suppressAnyReturnType) { + if(context.flags & NodeBuilderFlags.SuppressAnyReturnType) { if(returnTypeNode && returnTypeNode.kind === SyntaxKind.AnyKeyword) { returnTypeNode = undefined; } @@ -2733,6 +2776,8 @@ namespace ts { return parameterNode; } + // TODO: add meaning: SymbolFlags argument. + // TODO: add SymbolFormatFlags?? Yes to add outer type parameters. Defer UseOnlyExternalAliasing until a separate symbolbuilder PR. function symbolToName(symbol: Symbol, expectsIdentifier: true, context: NodeBuilderContext): Identifier; function symbolToName(symbol: Symbol, expectsIdentifier: false, context: NodeBuilderContext): EntityName; function symbolToName(symbol: Symbol, expectsIdentifier: boolean, context: NodeBuilderContext): EntityName { @@ -2826,6 +2871,7 @@ namespace ts { } } } + function getNameOfSymbol(symbol: Symbol, context: NodeBuilderContext): string { const declaration = firstOrUndefined(symbol.declarations); if (declaration) { diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index afafee51bf7..eebbe302898 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2947,8 +2947,9 @@ namespace ts { // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings, HeritageClauses = SingleLine | SpaceBetweenSiblings, - SingleLineTypeLiteralMembers = SpaceBetweenBraces | SpaceBetweenSiblings | Indented, // MultiLine | Indented, + SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings | Indented, // MultiLine | Indented, MultiLineTypeLiteralMembers = MultiLine | Indented, + TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 9dfd38a0a5c..172710f39aa 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -393,6 +393,18 @@ namespace ts { : node; } + export function createParenthesizedTypeNode(type: TypeNode) { + const parenthesizedTypeNode = createSynthesizedNode(SyntaxKind.ParenthesizedType) as ParenthesizedTypeNode; + parenthesizedTypeNode.type = type; + return parenthesizedTypeNode; + } + + export function updateParenthesizedTypeNode(node: ParenthesizedTypeNode, type: TypeNode) { + return node.type !== type + ? updateNode(createParenthesizedTypeNode(type), node) + : node; + } + export function createTypeLiteralNode(members: TypeElement[]) { const typeLiteralNode = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode; typeLiteralNode.members = createNodeArray(members); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 53507e3aa38..17df0243a1b 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2559,14 +2559,36 @@ namespace ts { export enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1 << 0, - allowQualifedNameInPlaceOfIdentifier = 1 << 1, - allowTypeParameterInQualifiedName = 1 << 2, - allowAnonymousIdentifier = 1 << 3, - allowEmptyUnionOrIntersection = 1 << 4, - allowEmptyTuple = 1 << 5, - suppressAnyReturnType = 1 << 6, - ignoreErrors = allowThisInObjectLiteral | allowQualifedNameInPlaceOfIdentifier | allowTypeParameterInQualifiedName | allowAnonymousIdentifier | allowEmptyUnionOrIntersection | allowEmptyTuple + // Options + NoTruncation = 1 << 0, // Don't truncate result + // TODO: part of emit. + WriteArrayAsGenericType = 1 << 1, // Write Array instead T[] + // TODO: part of emit. + UseTypeOfFunction = 1 << 2, // Write typeof instead of function type literal + // TODO: part of emit. + WriteArrowStyleSignature = 1 << 3, // Write arrow style signature + // TODO: turn it into a failing type reference? + WriteOwnNameForAnyLike = 1 << 4, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) + // TODO + WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature + // TODO + UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) + // TODO + UseTypeAliasValue = 1 << 7, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. + SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type. + // TODO + AddUndefined = 1 << 9, // Add undefined to types of initialized, non-optional parameters + + // Error handling + allowThisInObjectLiteral = 1 << 10, + allowQualifedNameInPlaceOfIdentifier = 1 << 11, + allowTypeParameterInQualifiedName = 1 << 12, + allowAnonymousIdentifier = 1 << 13, + allowEmptyUnionOrIntersection = 1 << 14, + allowEmptyTuple = 1 << 15, + + ignoreErrors = allowThisInObjectLiteral | allowQualifedNameInPlaceOfIdentifier | allowTypeParameterInQualifiedName | allowAnonymousIdentifier | allowEmptyUnionOrIntersection | allowEmptyTuple, + } export interface SymbolDisplayBuilder { diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 262520292e1..1e196a925f8 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -322,7 +322,8 @@ namespace ts { nodesVisitor((node).types, visitor, isTypeNode)); case SyntaxKind.ParenthesizedType: - throw Debug.fail("not implemented."); + return updateParenthesizedTypeNode(node, + visitNode((node).type, visitor, isTypeNode)); case SyntaxKind.TypeOperator: return updateTypeOperatorNode(node, visitNode((node).type, visitor, isTypeNode)); diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 0f636bb09ca..7c1a8c407fc 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -130,7 +130,7 @@ namespace ts.codefix { } function signatureToMethodDeclaration(signature: Signature, enclosingDeclaration: Node, body?: Block) { - const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.suppressAnyReturnType); + const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; From d35f6c3581943d5b473efa47f36c67707951cad6 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 4 May 2017 16:12:54 -0700 Subject: [PATCH 080/282] getNameOfDeclaration uniformly, including JS decls JS-style assignment declarations have a name, but it's not stored on the name property of the BinaryExpression. This commit adds `getNameOfDeclaration` to uniformly get the name of a declaration. It also reworks the declaration of `Declaration` so that accessing `name` is an error unless the type does *not* include BinaryExpression. --- src/compiler/binder.ts | 21 +++--- src/compiler/checker.ts | 102 +++++++++++++++----------- src/compiler/declarationEmitter.ts | 2 +- src/compiler/factory.ts | 7 +- src/compiler/transformers/es2015.ts | 4 +- src/compiler/types.ts | 58 ++++++++------- src/compiler/utilities.ts | 40 ++++++++-- src/harness/fourslash.ts | 2 +- src/services/codefixes/helpers.ts | 4 +- src/services/findAllReferences.ts | 2 +- src/services/formatting/formatting.ts | 2 +- src/services/goToDefinition.ts | 2 +- src/services/importTracker.ts | 5 +- src/services/navigateTo.ts | 37 ++++++---- src/services/navigationBar.ts | 12 +-- src/services/services.ts | 9 ++- src/services/utilities.ts | 2 +- 17 files changed, 184 insertions(+), 127 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 562a650a7f0..38cb93bff7e 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -227,12 +227,13 @@ namespace ts { // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node: Declaration): string { - if (node.name) { + const name = getNameOfDeclaration(node); + if (name) { if (isAmbientModule(node)) { - return isGlobalScopeAugmentation(node) ? "__global" : `"${(node.name).text}"`; + return isGlobalScopeAugmentation(node) ? "__global" : `"${(name).text}"`; } - if (node.name.kind === SyntaxKind.ComputedPropertyName) { - const nameExpression = (node.name).expression; + if (name.kind === SyntaxKind.ComputedPropertyName) { + const nameExpression = (name).expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -241,7 +242,7 @@ namespace ts { Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); return getPropertyNameForKnownSymbolName((nameExpression).name.text); } - return (node.name).text; + return (name).text; } switch (node.kind) { case SyntaxKind.Constructor: @@ -303,7 +304,7 @@ namespace ts { } function getDisplayName(node: Declaration): string { - return node.name ? declarationNameToString(node.name) : getDeclarationName(node); + return (node as RealDeclaration).name ? declarationNameToString((node as RealDeclaration).name) : getDeclarationName(node); } /** @@ -366,8 +367,8 @@ namespace ts { symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } else { - if (node.name) { - node.name.parent = node; + if ((node as RealDeclaration).name) { + (node as RealDeclaration).name.parent = node; } // Report errors every position with duplicate declaration @@ -396,9 +397,9 @@ namespace ts { } forEach(symbol.declarations, declaration => { - file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(declaration) || declaration, message, getDisplayName(declaration))); }); - file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(node) || node, message, getDisplayName(node))); symbol = createSymbol(SymbolFlags.None, name); } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 603f45cbf07..8979510461e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -580,16 +580,16 @@ namespace ts { recordMergedSymbol(target, source); } else if (target.flags & SymbolFlags.NamespaceModule) { - error(source.declarations[0].name, Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { const message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; forEach(source.declarations, node => { - error(node.name ? node.name : node, message, symbolToString(source)); + error(getNameOfDeclaration(node) || node, message, symbolToString(source)); }); forEach(target.declarations, node => { - error(node.name ? node.name : node, message, symbolToString(source)); + error(getNameOfDeclaration(node) || node, message, symbolToString(source)); }); } } @@ -1240,13 +1240,13 @@ namespace ts { if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & SymbolFlags.BlockScopedVariable) { - error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } else if (result.flags & SymbolFlags.Class) { - error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } else if (result.flags & SymbolFlags.Enum) { - error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } } } @@ -2809,8 +2809,9 @@ namespace ts { function getNameOfSymbol(symbol: Symbol): string { const declaration = firstOrUndefined(symbol.declarations); if (declaration) { - if (declaration.name) { - return declarationNameToString(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { return declarationNameToString((declaration.parent).name); @@ -2897,8 +2898,9 @@ namespace ts { function getNameOfSymbol(symbol: Symbol): string { if (symbol.declarations && symbol.declarations.length) { const declaration = symbol.declarations[0]; - if (declaration.name) { - return declarationNameToString(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { return declarationNameToString((declaration.parent).name); @@ -6234,8 +6236,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return (node).name.kind === SyntaxKind.ComputedPropertyName - && traverse((node).name); + return (node).name.kind === SyntaxKind.ComputedPropertyName + && traverse((node).name); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && forEachChild(node, traverse); @@ -6315,8 +6317,9 @@ namespace ts { type = anyType; if (noImplicitAny) { const declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name)); + const name = getNameOfDeclaration(declaration); + if (name) { + error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name)); } else { error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -9931,7 +9934,7 @@ namespace ts { default: diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration: Declaration, type: Type) { @@ -11836,7 +11839,7 @@ namespace ts { if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -15399,7 +15402,7 @@ namespace ts { // only the class declaration node will have the Abstract flag set. const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && getModifierFlags(valueDecl) & ModifierFlags.Abstract) { - error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(valueDecl.name)); + error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -15863,11 +15866,11 @@ namespace ts { const links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + const name = getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === SyntaxKind.ObjectBindingPattern || - parameter.valueDeclaration.name.kind === SyntaxKind.ArrayBindingPattern)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === SyntaxKind.ObjectBindingPattern || name.kind === SyntaxKind.ArrayBindingPattern)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -17711,7 +17714,7 @@ namespace ts { } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, Diagnostics.Duplicate_identifier_0, memberName); + error(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName); error(member.name, Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -17812,7 +17815,8 @@ namespace ts { } function containsSuperCallAsComputedPropertyName(n: Declaration): boolean { - return n.name && containsSuperCall(n.name); + const name = getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n: Node): boolean { @@ -18106,17 +18110,18 @@ namespace ts { forEach(overloads, o => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; + const name = getNameOfDeclaration(o); if (deviation & ModifierFlags.Export) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(name, Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & ModifierFlags.Ambient) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(name, Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (ModifierFlags.Private | ModifierFlags.Protected)) { - error(o.name || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(name || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & ModifierFlags.Abstract) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(name, Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -18128,7 +18133,7 @@ namespace ts { forEach(overloads, o => { const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; if (deviation) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -18264,7 +18269,7 @@ namespace ts { if (duplicateFunctionDeclaration) { forEach(declarations, declaration => { - error(declaration.name, Diagnostics.Duplicate_function_implementation); + error(getNameOfDeclaration(declaration), Diagnostics.Duplicate_function_implementation); }); } @@ -18346,12 +18351,13 @@ namespace ts { for (const d of symbol.declarations) { const declarationSpaces = getDeclarationSpaces(d); + const name = getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name)); + error(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(d.name)); + error(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name)); } } } @@ -18990,15 +18996,16 @@ namespace ts { if (!local.isReferenced) { if (local.valueDeclaration && getRootDeclaration(local.valueDeclaration).kind === SyntaxKind.Parameter) { const parameter = getRootDeclaration(local.valueDeclaration); + const name = getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !isParameterPropertyDeclaration(parameter) && !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - forEach(local.declarations, d => errorUnusedLocal(d.name || d, local.name)); + forEach(local.declarations, d => errorUnusedLocal(getNameOfDeclaration(d) || d, local.name)); } } }); @@ -19082,7 +19089,7 @@ namespace ts { if (!local.isReferenced && !local.exportSymbol) { for (const declaration of local.declarations) { if (!isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(getNameOfDeclaration(declaration), local.name); } } } @@ -19161,7 +19168,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error((node).name, Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -19176,7 +19183,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureNewTarget) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error((node).name, Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -19475,7 +19482,7 @@ namespace ts { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + error(getNameOfDeclaration(symbol.valueDeclaration), Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } } @@ -20306,16 +20313,23 @@ namespace ts { const propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } + let errorNode: Node; + if (propDeclaration && propDeclaration.kind === SyntaxKind.BinaryExpression) { + const specialAssignmentKind = getSpecialPropertyAssignmentKind(propDeclaration as BinaryExpression); + if (specialAssignmentKind === SpecialPropertyAssignmentKind.Property || + specialAssignmentKind === SpecialPropertyAssignmentKind.PrototypeProperty || + specialAssignmentKind === SpecialPropertyAssignmentKind.ThisProperty) { + errorNode = propDeclaration; + } + } // perform property check if property or indexer is declared in 'type' // this allows to rule out cases when both property and indexer are inherited from the base class - let errorNode: Node; if (propDeclaration && - (getSpecialPropertyAssignmentKind(propDeclaration as BinaryExpression) === SpecialPropertyAssignmentKind.ThisProperty || - propDeclaration.name.kind === SyntaxKind.ComputedPropertyName || + (getNameOfDeclaration(propDeclaration).kind === SyntaxKind.ComputedPropertyName || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -20679,7 +20693,7 @@ namespace ts { errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -21010,7 +21024,7 @@ namespace ts { // check that const is placed\omitted on all enum declarations forEach(enumSymbol.declarations, decl => { if (isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -21903,7 +21917,7 @@ namespace ts { function isTypeDeclarationName(name: Node): boolean { return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && - (name.parent).name === name; + (name.parent).name === name; } function isTypeDeclaration(node: Node): boolean { diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 2bd8d5971fb..0a7f9a2a3ec 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1134,7 +1134,7 @@ namespace ts { return { diagnosticMessage, errorNode: node, - typeName: (node.parent.parent).name + typeName: getNameOfDeclaration(node.parent.parent) }; } } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index cce95c23c22..1a8b91c8ff2 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3064,9 +3064,10 @@ namespace ts { } function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) { - if (node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name)) { - const name = getMutableClone(node.name); - emitFlags |= getEmitFlags(node.name); + const nodeName = getNameOfDeclaration(node); + if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { + const name = getMutableClone(nodeName); + emitFlags |= getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap; if (!allowComments) emitFlags |= EmitFlags.NoComments; if (emitFlags) setEmitFlags(name, emitFlags); diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 734fbcaeb16..188da04b36c 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -3748,7 +3748,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.VariableDeclaration: - return (parent).name === node + return (parent).name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -3781,7 +3781,7 @@ namespace ts { if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings && !isInternalName(node)) { const declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return setTextRange(getGeneratedNameForNode(declaration.name), node); + return setTextRange(getGeneratedNameForNode(getNameOfDeclaration(declaration)), node); } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 7e45dabaf95..51e9d6717ee 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -603,12 +603,15 @@ namespace ts { export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; - export interface Declaration extends Node { + export interface RealDeclaration extends Node { _declarationBrand: any; name?: DeclarationName; } - export interface DeclarationStatement extends Declaration, Statement { + // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files + export type Declaration = RealDeclaration | BinaryExpression; + + export interface DeclarationStatement extends RealDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } @@ -622,7 +625,7 @@ namespace ts { expression: LeftHandSideExpression; } - export interface TypeParameterDeclaration extends Declaration { + export interface TypeParameterDeclaration extends RealDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -633,7 +636,7 @@ namespace ts { expression?: Expression; } - export interface SignatureDeclaration extends Declaration { + export interface SignatureDeclaration extends RealDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -650,7 +653,7 @@ namespace ts { export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends Declaration { + export interface VariableDeclaration extends RealDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; // Declared variable name @@ -664,7 +667,7 @@ namespace ts { declarations: NodeArray; } - export interface ParameterDeclaration extends Declaration { + export interface ParameterDeclaration extends RealDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; // Present on rest parameter @@ -674,7 +677,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface BindingElement extends Declaration { + export interface BindingElement extends RealDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; // Binding property name (in object binding pattern) @@ -699,7 +702,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface ObjectLiteralElement extends Declaration { + export interface ObjectLiteralElement extends RealDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -743,7 +746,7 @@ namespace ts { // SyntaxKind.ShorthandPropertyAssignment // SyntaxKind.EnumMember // SyntaxKind.JSDocPropertyTag - export interface VariableLikeDeclaration extends Declaration { + export interface VariableLikeDeclaration extends RealDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -752,7 +755,7 @@ namespace ts { initializer?: Expression; } - export interface PropertyLikeDeclaration extends Declaration { + export interface PropertyLikeDeclaration extends RealDeclaration { name: PropertyName; } @@ -901,7 +904,7 @@ namespace ts { } // A TypeLiteral is the declaration node for an anonymous symbol. - export interface TypeLiteralNode extends TypeNode, Declaration { + export interface TypeLiteralNode extends TypeNode, RealDeclaration { kind: SyntaxKind.TypeLiteral; members: NodeArray; } @@ -945,7 +948,7 @@ namespace ts { indexType: TypeNode; } - export interface MappedTypeNode extends TypeNode, Declaration { + export interface MappedTypeNode extends TypeNode, RealDeclaration { kind: SyntaxKind.MappedType; parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; @@ -1216,8 +1219,7 @@ namespace ts { export type BinaryOperatorToken = Token; - // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files - export interface BinaryExpression extends Expression, Declaration { + export interface BinaryExpression extends Expression { kind: SyntaxKind.BinaryExpression; left: Expression; operatorToken: BinaryOperatorToken; @@ -1403,7 +1405,7 @@ namespace ts { * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) */ - export interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { + export interface ObjectLiteralExpressionBase extends PrimaryExpression, RealDeclaration { properties: NodeArray; } @@ -1417,7 +1419,7 @@ namespace ts { export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - export interface PropertyAccessExpression extends MemberExpression, Declaration { + export interface PropertyAccessExpression extends MemberExpression, RealDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1449,7 +1451,7 @@ namespace ts { | SuperElementAccessExpression ; - export interface CallExpression extends LeftHandSideExpression, Declaration { + export interface CallExpression extends LeftHandSideExpression, RealDeclaration { kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1468,7 +1470,7 @@ namespace ts { typeArguments?: NodeArray; } - export interface NewExpression extends PrimaryExpression, Declaration { + export interface NewExpression extends PrimaryExpression, RealDeclaration { kind: SyntaxKind.NewExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1762,7 +1764,7 @@ namespace ts { export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - export interface ClassLikeDeclaration extends Declaration { + export interface ClassLikeDeclaration extends RealDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1778,12 +1780,12 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export interface ClassElement extends Declaration { + export interface ClassElement extends RealDeclaration { _classElementBrand: any; name?: PropertyName; } - export interface TypeElement extends Declaration { + export interface TypeElement extends RealDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1811,7 +1813,7 @@ namespace ts { type: TypeNode; } - export interface EnumMember extends Declaration { + export interface EnumMember extends RealDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; // This does include ComputedPropertyName, but the parser will give an error @@ -1900,14 +1902,14 @@ namespace ts { // import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns } // import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} // import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} - export interface ImportClause extends Declaration { + export interface ImportClause extends RealDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; // Default binding namedBindings?: NamedImportBindings; } - export interface NamespaceImport extends Declaration { + export interface NamespaceImport extends RealDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1940,14 +1942,14 @@ namespace ts { export type NamedImportsOrExports = NamedImports | NamedExports; - export interface ImportSpecifier extends Declaration { + export interface ImportSpecifier extends RealDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) name: Identifier; // Declared name } - export interface ExportSpecifier extends Declaration { + export interface ExportSpecifier extends RealDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) @@ -2113,7 +2115,7 @@ namespace ts { typeExpression: JSDocTypeExpression; } - export interface JSDocTypedefTag extends JSDocTag, Declaration { + export interface JSDocTypedefTag extends JSDocTag, RealDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2247,7 +2249,7 @@ namespace ts { // Source files are declarations when they are external modules. - export interface SourceFile extends Declaration { + export interface SourceFile extends RealDeclaration { kind: SyntaxKind.SourceFile; statements: NodeArray; endOfFileToken: Token; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index f1b181a03b0..5b1cbb849bc 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -11,6 +11,36 @@ namespace ts { isTypeReferenceDirective?: boolean; } + export function getNameOfDeclaration(declaration: Declaration): DeclarationName { + if (!declaration) { + return undefined; + } + if (declaration.kind === SyntaxKind.BinaryExpression) { + const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression); + const lhs = (declaration as BinaryExpression).left; + switch (kind) { + case SpecialPropertyAssignmentKind.None: + case SpecialPropertyAssignmentKind.ModuleExports: + return undefined; + case SpecialPropertyAssignmentKind.ExportsProperty: + if (lhs.kind === SyntaxKind.Identifier) { + return (lhs as PropertyAccessExpression).name; + } + else { + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + case SpecialPropertyAssignmentKind.ThisProperty: + case SpecialPropertyAssignmentKind.Property: + return (lhs as PropertyAccessExpression).name; + case SpecialPropertyAssignmentKind.PrototypeProperty: + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + } + else { + return declaration.name; + } + } + export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { const declarations = symbol.declarations; if (declarations) { @@ -566,7 +596,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.TypeAliasDeclaration: - errorNode = (node).name; + errorNode = (node).name; break; case SyntaxKind.ArrowFunction: return getErrorSpanForArrowFunction(sourceFile, node); @@ -1770,7 +1800,7 @@ namespace ts { } if (isDeclaration(parent)) { - return (parent).name === name; + return parent.name === name; } return false; @@ -1796,7 +1826,7 @@ namespace ts { case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyAccessExpression: // Name in member declaration or property name in property access - return (parent).name === node; + return (parent).name === node; case SyntaxKind.QualifiedName: // Name on right hand side of dot in a type query if ((parent).right === node) { @@ -1994,7 +2024,7 @@ namespace ts { * Symbol. */ export function hasDynamicName(declaration: Declaration): boolean { - return declaration.name && isDynamicName(declaration.name); + return getNameOfDeclaration(declaration) && isDynamicName(getNameOfDeclaration(declaration)); } export function isDynamicName(name: DeclarationName): boolean { @@ -4071,7 +4101,7 @@ namespace ts { || kind === SyntaxKind.MergeDeclarationMarker; } - export function isDeclaration(node: Node): node is Declaration { + export function isDeclaration(node: Node): node is RealDeclaration { return isDeclarationKind(node.kind); } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a56d21ae345..83d27c951be 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -655,7 +655,7 @@ namespace FourSlash { ts.zipWith(endMarkers, definitions, (endMarker, definition, i) => { const marker = this.getMarkerByName(endMarker); if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) { - this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`); + this.raiseError(`goToDefinition failed for definition ${endMarker} (${i}): expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`); } }); } diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 0de04d7a9b9..6585e994543 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -63,7 +63,7 @@ namespace ts.codefix { const declaration = declarations[0] as Declaration; // Clone name to remove leading trivia. - const name = getSynthesizedClone(declaration.name); + const name = getSynthesizedClone(getNameOfDeclaration(declaration)) as PropertyName; const visibilityModifier = createVisibilityModifier(getModifierFlags(declaration)); const modifiers = visibilityModifier ? createNodeArray([visibilityModifier]) : undefined; const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -231,4 +231,4 @@ namespace ts.codefix { } return undefined; } -} \ No newline at end of file +} diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index fd717fc546e..9ca90cfd5ef 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -908,7 +908,7 @@ namespace ts.FindAllReferences.Core { * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & SymbolFlags.Transient) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 5c2171cc4ae..d5bd33e33cc 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -487,7 +487,7 @@ namespace ts.formatting { // falls through case SyntaxKind.PropertyDeclaration: case SyntaxKind.Parameter: - return (node).name.kind; + return getNameOfDeclaration(node).kind; } } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index f2602903be3..09d1f2a248c 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -235,7 +235,7 @@ namespace ts.GoToDefinition { /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node: Declaration, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index c94d5cc3143..6e9a12a4c4d 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -537,7 +537,10 @@ namespace ts.FindAllReferences { return symbol.name; } - const name = forEach(symbol.declarations, ({ name }) => name && name.kind === SyntaxKind.Identifier && name.text); + const name = forEach(symbol.declarations, decl => { + const name = getNameOfDeclaration(decl); + return name && name.kind === SyntaxKind.Identifier && name.text; + }); Debug.assert(!!name); return name; } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 2c8d43b535b..c29b29143c5 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -97,17 +97,20 @@ namespace ts.NavigateTo { } function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]) { - if (declaration && declaration.name) { - const text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - return tryAddComputedPropertyName((declaration.name).expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + const name = getNameOfDeclaration(declaration); + if (name) { + const text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === SyntaxKind.ComputedPropertyName) { + return tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } @@ -143,8 +146,9 @@ namespace ts.NavigateTo { // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - if (!tryAddComputedPropertyName((declaration.name).expression, containers, /*includeLastPortion*/ false)) { + const name = getNameOfDeclaration(declaration); + if (name.kind === SyntaxKind.ComputedPropertyName) { + if (!tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -190,6 +194,7 @@ namespace ts.NavigateTo { function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { const declaration = rawItem.declaration; const container = getContainerNode(declaration); + const containerName = container && getNameOfDeclaration(container); return { name: rawItem.name, kind: getNodeKind(declaration), @@ -199,9 +204,9 @@ namespace ts.NavigateTo { fileName: rawItem.fileName, textSpan: createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? (container.name).text : "", - containerKind: container && container.name ? getNodeKind(container) : "" + containerName: containerName ? (containerName).text : "", + containerKind: containerName ? getNodeKind(container) : "" }; } } -} \ No newline at end of file +} diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 7a2508fcfd6..819202ff6f4 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -279,8 +279,8 @@ namespace ts.NavigationBar { function mergeChildren(children: NavigationBarNode[]): void { const nameToItems = createMap(); filterMutate(children, child => { - const decl = child.node; - const name = decl.name && nodeText(decl.name); + const declName = getNameOfDeclaration(child.node); + const name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -378,9 +378,9 @@ namespace ts.NavigationBar { return getModuleName(node); } - const decl = node; - if (decl.name) { - return getPropertyNameForPropertyNameNode(decl.name); + const declName = getNameOfDeclaration(node); + if (declName) { + return getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case SyntaxKind.FunctionExpression: @@ -399,7 +399,7 @@ namespace ts.NavigationBar { return getModuleName(node); } - const name = (node).name; + const name = getNameOfDeclaration(node); if (name) { const text = nodeText(name); if (text.length > 0) { diff --git a/src/services/services.ts b/src/services/services.ts index fa15568f86e..1b4678b5dbc 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -578,14 +578,15 @@ namespace ts { } function getDeclarationName(declaration: Declaration) { - if (declaration.name) { - const result = getTextOfIdentifierOrLiteral(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + const result = getTextOfIdentifierOrLiteral(name); if (result !== undefined) { return result; } - if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - const expr = (declaration.name).expression; + if (name.kind === SyntaxKind.ComputedPropertyName) { + const expr = (name).expression; if (expr.kind === SyntaxKind.PropertyAccessExpression) { return (expr).name.text; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index e884b342fef..065c42245f6 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -238,7 +238,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.ModuleDeclaration: - return (node.parent).name === node; + return getNameOfDeclaration(node.parent) === node; case SyntaxKind.ElementAccessExpression: return (node.parent).argumentExpression === node; case SyntaxKind.ComputedPropertyName: From aceadeb04b06356dd7d3b4fc2f94d08e29e745e0 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 4 May 2017 16:13:32 -0700 Subject: [PATCH 081/282] Update baselines --- .../reference/checkJsFiles_noErrorLocation.errors.txt | 4 ++-- tests/cases/fourslash/javaScriptClass3.ts | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt b/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt index 758b295a49d..d9104608284 100644 --- a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt +++ b/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. +tests/cases/compiler/a.js(14,10): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. ==== tests/cases/compiler/a.js (1 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member constructor() { super(); this.foo = () => 3; - ~~~~~~~~~~~~~~~~~~ + ~~~ !!! error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. } } diff --git a/tests/cases/fourslash/javaScriptClass3.ts b/tests/cases/fourslash/javaScriptClass3.ts index 41ce79b35eb..fd67f6f53a5 100644 --- a/tests/cases/fourslash/javaScriptClass3.ts +++ b/tests/cases/fourslash/javaScriptClass3.ts @@ -1,13 +1,13 @@ /// -// In an inferred class, we can to-to-def successfully +// In an inferred class, we can go-to-def successfully // @allowNonTsExtensions: true // @Filename: Foo.js //// class Foo { //// constructor() { -//// /*dst1*/this.alpha = 10; -//// /*dst2*/this.beta = 'gamma'; +//// this./*dst1*/alpha = 10; +//// this./*dst2*/beta = 'gamma'; //// } //// method() { return this.alpha; } //// } From efe502e609a579dae82330f0194b9689f2af7b64 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 4 May 2017 17:04:37 -0700 Subject: [PATCH 082/282] Address PR comments --- src/compiler/checker.ts | 11 -------- src/compiler/declarationEmitter.ts | 40 +++++++++++------------------- src/compiler/types.ts | 1 - 3 files changed, 14 insertions(+), 38 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dac3dce3b32..3803f5d81fa 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22641,16 +22641,6 @@ namespace ts { getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - const baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol && !(baseType.flags & TypeFlags.Intersection)) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name: string): boolean { return globals.has(name); } @@ -22744,7 +22734,6 @@ namespace ts { writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression, - writeBaseConstructorTypeOfClass, isSymbolAccessible, isEntityNameVisible, getConstantValue: node => { diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 7251fec169f..d7ad2c3a78d 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -617,7 +617,7 @@ namespace ts { if (!noDeclare) { write("declare "); } - write("var "); + write("const "); write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = () => diagnostic; @@ -1096,7 +1096,7 @@ namespace ts { } } - function emitHeritageClause(className: Identifier, typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) { + function emitHeritageClause(typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -1109,16 +1109,6 @@ namespace ts { else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass( - enclosingDeclaration as ClassLikeDeclaration, - enclosingDeclaration, - TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, - writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError(): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; @@ -1158,12 +1148,14 @@ namespace ts { enclosingDeclaration = node; const baseTypeNode = getClassExtendsHeritageClauseElement(node); let tempVarName: string; - if (isNonNullExpression(baseTypeNode)) { - tempVarName = emitTempVariableDeclaration(baseTypeNode.expression, `_${node.name.text}_intersection_base`, { - diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, - errorNode: baseTypeNode, - typeName: node.name - }); + if (baseTypeNode && !isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === SyntaxKind.NullKeyword ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, `${node.name.text}_base`, { + diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }); } emitJsDocComments(node); @@ -1175,7 +1167,7 @@ namespace ts { writeTextOfNode(currentText, node.name); emitTypeParameters(node.typeParameters); if (baseTypeNode) { - if (isNonNullExpression(baseTypeNode)) { + if (!isEntityNameExpression(baseTypeNode.expression)) { write(" extends "); write(tempVarName); if (baseTypeNode.typeArguments) { @@ -1185,10 +1177,10 @@ namespace ts { } } else { - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); } } - emitHeritageClause(node.name, getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -1210,7 +1202,7 @@ namespace ts { emitTypeParameters(node.typeParameters); const interfaceExtendsTypes = filter(getInterfaceBaseTypeNodes(node), base => isEntityNameExpression(base.expression)); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -1222,10 +1214,6 @@ namespace ts { enclosingDeclaration = prevEnclosingDeclaration; } - function isNonNullExpression(node: ExpressionWithTypeArguments) { - return node && !isEntityNameExpression(node.expression) && node.expression.kind !== SyntaxKind.NullKeyword; - } - function emitPropertyDeclaration(node: Declaration) { if (hasDynamicName(node)) { return; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 57cf17f7100..6bcd24292e8 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2727,7 +2727,6 @@ namespace ts { writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; - writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant From 58e72fe1b6c8b61f409b80c5b85ad5b1e5050e77 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 4 May 2017 17:05:09 -0700 Subject: [PATCH 083/282] Update baselines --- .../declarationEmitDefaultExport5.js | 2 +- .../declarationEmitDefaultExport6.js | 2 +- .../declarationEmitDefaultExport8.js | 2 +- ...arationEmitDefaultExportWithTempVarName.js | 2 +- ...efaultExportWithTempVarNameWithBundling.js | 2 +- .../declarationEmitExpressionInExtends2.js | 4 ++-- ...declarationEmitInferedDefaultExportType.js | 2 +- ...eclarationEmitInferedDefaultExportType2.js | 2 +- .../reference/es5ExportDefaultExpression.js | 2 +- .../reference/es6ExportDefaultExpression.js | 2 +- ...rtDefaultBindingFollowedWithNamedImport.js | 2 +- ...indingFollowedWithNamedImportWithExport.js | 2 +- .../exportClassExtendingIntersection.js | 4 ++-- .../reference/mixinAccessModifiers.js | 24 +++++++++---------- 14 files changed, 27 insertions(+), 27 deletions(-) diff --git a/tests/baselines/reference/declarationEmitDefaultExport5.js b/tests/baselines/reference/declarationEmitDefaultExport5.js index 701318b14d7..427463be5ab 100644 --- a/tests/baselines/reference/declarationEmitDefaultExport5.js +++ b/tests/baselines/reference/declarationEmitDefaultExport5.js @@ -7,5 +7,5 @@ export default 1 + 2; //// [declarationEmitDefaultExport5.d.ts] -declare var _default: number; +declare const _default: number; export default _default; diff --git a/tests/baselines/reference/declarationEmitDefaultExport6.js b/tests/baselines/reference/declarationEmitDefaultExport6.js index d56609e8534..1391ec0b4f2 100644 --- a/tests/baselines/reference/declarationEmitDefaultExport6.js +++ b/tests/baselines/reference/declarationEmitDefaultExport6.js @@ -12,5 +12,5 @@ export default new A(); //// [declarationEmitDefaultExport6.d.ts] export declare class A { } -declare var _default: A; +declare const _default: A; export default _default; diff --git a/tests/baselines/reference/declarationEmitDefaultExport8.js b/tests/baselines/reference/declarationEmitDefaultExport8.js index 5511c5981e5..33ef87bf744 100644 --- a/tests/baselines/reference/declarationEmitDefaultExport8.js +++ b/tests/baselines/reference/declarationEmitDefaultExport8.js @@ -13,5 +13,5 @@ export default 1 + 2; //// [declarationEmitDefaultExport8.d.ts] declare var _default: number; export { _default as d }; -declare var _default_1: number; +declare const _default_1: number; export default _default_1; diff --git a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js index 44e0560132f..11fddc855b2 100644 --- a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js +++ b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarName.js @@ -15,5 +15,5 @@ System.register([], function (exports_1, context_1) { //// [pi.d.ts] -declare var _default: 3.14159; +declare const _default: 3.14159; export default _default; diff --git a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js index 6ac6cf29018..31749d1773e 100644 --- a/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js +++ b/tests/baselines/reference/declarationEmitDefaultExportWithTempVarNameWithBundling.js @@ -16,6 +16,6 @@ System.register("pi", [], function (exports_1, context_1) { //// [app.d.ts] declare module "pi" { - var _default: 3.14159; + const _default: 3.14159; export default _default; } diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends2.js b/tests/baselines/reference/declarationEmitExpressionInExtends2.js index ed3bc9d96f3..a49175a3dc4 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends2.js +++ b/tests/baselines/reference/declarationEmitExpressionInExtends2.js @@ -45,6 +45,6 @@ declare class C { y: U; } declare function getClass(c: T): typeof C; -declare var _MyClass_intersection_base: typeof C; -declare class MyClass extends _MyClass_intersection_base { +declare const MyClass_base: typeof C; +declare class MyClass extends MyClass_base { } diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType.js b/tests/baselines/reference/declarationEmitInferedDefaultExportType.js index 4d9eb47641a..a9eca8d1161 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType.js +++ b/tests/baselines/reference/declarationEmitInferedDefaultExportType.js @@ -18,7 +18,7 @@ exports["default"] = { //// [declarationEmitInferedDefaultExportType.d.ts] -declare var _default: { +declare const _default: { foo: any[]; bar: any; baz: any; diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js b/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js index 96c16829d7e..fde31605659 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js +++ b/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js @@ -16,7 +16,7 @@ module.exports = { //// [declarationEmitInferedDefaultExportType2.d.ts] -declare var _default: { +declare const _default: { foo: any[]; bar: any; baz: any; diff --git a/tests/baselines/reference/es5ExportDefaultExpression.js b/tests/baselines/reference/es5ExportDefaultExpression.js index 3db562da647..b365018b2f3 100644 --- a/tests/baselines/reference/es5ExportDefaultExpression.js +++ b/tests/baselines/reference/es5ExportDefaultExpression.js @@ -9,5 +9,5 @@ exports.default = (1 + 2); //// [es5ExportDefaultExpression.d.ts] -declare var _default: number; +declare const _default: number; export default _default; diff --git a/tests/baselines/reference/es6ExportDefaultExpression.js b/tests/baselines/reference/es6ExportDefaultExpression.js index ce6dcd71b90..059aae49598 100644 --- a/tests/baselines/reference/es6ExportDefaultExpression.js +++ b/tests/baselines/reference/es6ExportDefaultExpression.js @@ -7,5 +7,5 @@ export default (1 + 2); //// [es6ExportDefaultExpression.d.ts] -declare var _default: number; +declare const _default: number; export default _default; diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js index bccb0a9dea4..a5b7700c36c 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport.js @@ -48,6 +48,6 @@ var x1 = es6ImportDefaultBindingFollowedWithNamedImport_0_5.m; export declare var a: number; export declare var x: number; export declare var m: number; -declare var _default: {}; +declare const _default: {}; export default _default; //// [es6ImportDefaultBindingFollowedWithNamedImport_1.d.ts] diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js index 756ae6a999b..ff8c1059ad1 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportWithExport.js @@ -47,7 +47,7 @@ define(["require", "exports", "server", "server", "server", "server", "server"], export declare var a: number; export declare var x: number; export declare var m: number; -declare var _default: {}; +declare const _default: {}; export default _default; //// [client.d.ts] export declare var x1: number; diff --git a/tests/baselines/reference/exportClassExtendingIntersection.js b/tests/baselines/reference/exportClassExtendingIntersection.js index cfb3fd66842..919f1695093 100644 --- a/tests/baselines/reference/exportClassExtendingIntersection.js +++ b/tests/baselines/reference/exportClassExtendingIntersection.js @@ -114,8 +114,8 @@ export declare function MyMixin>>(base: T //// [FinalClass.d.ts] import { MyBaseClass } from './BaseClass'; import { MyMixin } from './MixinClass'; -declare var _MyExtendedClass_intersection_base: typeof MyBaseClass & (new (...args: any[]) => MyMixin); -export declare class MyExtendedClass extends _MyExtendedClass_intersection_base { +declare const MyExtendedClass_base: typeof MyBaseClass & (new (...args: any[]) => MyMixin); +export declare class MyExtendedClass extends MyExtendedClass_base { extendedClassProperty: number; } //// [Main.d.ts] diff --git a/tests/baselines/reference/mixinAccessModifiers.js b/tests/baselines/reference/mixinAccessModifiers.js index 9abb2d00722..736808455bb 100644 --- a/tests/baselines/reference/mixinAccessModifiers.js +++ b/tests/baselines/reference/mixinAccessModifiers.js @@ -302,27 +302,27 @@ declare function f4(x: Protected & Protected2): void; declare function f5(x: Protected & Public): void; declare function f6(x: Public & Public2): void; declare function Mix(c1: T, c2: U): T & U; -declare var _C1_intersection_base: typeof Private & typeof Private2; -declare class C1 extends _C1_intersection_base { +declare const C1_base: typeof Private & typeof Private2; +declare class C1 extends C1_base { } -declare var _C2_intersection_base: typeof Private & typeof Protected; -declare class C2 extends _C2_intersection_base { +declare const C2_base: typeof Private & typeof Protected; +declare class C2 extends C2_base { } -declare var _C3_intersection_base: typeof Private & typeof Public; -declare class C3 extends _C3_intersection_base { +declare const C3_base: typeof Private & typeof Public; +declare class C3 extends C3_base { } -declare var _C4_intersection_base: typeof Protected & typeof Protected2; -declare class C4 extends _C4_intersection_base { +declare const C4_base: typeof Protected & typeof Protected2; +declare class C4 extends C4_base { f(c4: C4, c5: C5, c6: C6): void; static g(): void; } -declare var _C5_intersection_base: typeof Protected & typeof Public; -declare class C5 extends _C5_intersection_base { +declare const C5_base: typeof Protected & typeof Public; +declare class C5 extends C5_base { f(c4: C4, c5: C5, c6: C6): void; static g(): void; } -declare var _C6_intersection_base: typeof Public & typeof Public2; -declare class C6 extends _C6_intersection_base { +declare const C6_base: typeof Public & typeof Public2; +declare class C6 extends C6_base { f(c4: C4, c5: C5, c6: C6): void; static g(): void; } From f619d5add4818bae0e7005fc085f8c4950f702b1 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Thu, 4 May 2017 17:12:39 -0700 Subject: [PATCH 084/282] Allow excess property in spread attributes but also check if any explicitly specified attributes are correct --- src/compiler/checker.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c2e88424c42..b90028993ea 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13330,10 +13330,11 @@ namespace ts { } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - if (explicitlySpecifyChildrenAttribute) { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } @@ -13355,6 +13356,7 @@ namespace ts { */ function createJsxAttributesType(symbol: Symbol, attributesTable: Map) { const result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + // Spread object doesn't have freshness flag to allow excess attributes as it is very common for parent component to spread its "props" to other components in its render method. const freshObjectLiteralFlag = spread !== emptyObjectType || compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag; result.objectFlags |= ObjectFlags.ObjectLiteral; @@ -13907,9 +13909,11 @@ namespace ts { error(openingLikeElement, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - const isAssignableToTargetAttributes = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); - // TODO (yuisu): comment - if (isAssignableToTargetAttributes && sourceAttributesType !== anyType && !(sourceAttributesType.flags & TypeFlags.FreshLiteral)) { + checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // If sourceAttributesType has spread (e.g the type doesn't have freshness flag) after we check for assignability, we will do another pass to check that + // all explicitly specified attributes have correct name corresponding with target (as those will be assignable as spread type allows excess properties) + // Note: if the type of these explicitly specified attributes do not match it will be an error during above assignability check. + if (sourceAttributesType !== anyType && !(sourceAttributesType.flags & TypeFlags.FreshLiteral)) { for (const attribute of openingLikeElement.attributes.properties) { if (isJsxAttribute(attribute) && !getPropertyOfType(targetAttributesType, attribute.name.text)) { error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); From d103504ba668ff3522a0320604c1342c95dd59a7 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Thu, 4 May 2017 17:12:52 -0700 Subject: [PATCH 085/282] Update tests anad baselines --- .../checkJsxChildrenProperty2.errors.txt | 5 +-- ...StringLiteralsInJsxAttributes02.errors.txt | 35 ++++++++-------- .../tsxAttributeResolution3.errors.txt | 9 +--- .../reference/tsxAttributeResolution3.js | 4 +- ...tsxSpreadAttributesResolution12.errors.txt | 13 +++++- .../tsxSpreadAttributesResolution12.js | 3 ++ .../tsxSpreadAttributesResolution2.errors.txt | 27 +++++++++++- .../tsxSpreadAttributesResolution2.js | 6 ++- .../tsxSpreadAttributesResolution5.errors.txt | 11 ++--- .../tsxSpreadAttributesResolution5.js | 4 +- ...elessFunctionComponentOverload4.errors.txt | 17 +++----- .../tsxStatelessFunctionComponentOverload4.js | 4 +- ...elessFunctionComponentOverload5.errors.txt | 41 +++++++++++++------ ...tsxStatelessFunctionComponents1.errors.txt | 9 +--- .../tsxStatelessFunctionComponents1.js | 4 +- .../jsx/tsxAttributeResolution3.tsx | 2 +- .../jsx/tsxSpreadAttributesResolution12.tsx | 2 + .../jsx/tsxSpreadAttributesResolution2.tsx | 4 +- .../jsx/tsxSpreadAttributesResolution5.tsx | 2 +- ...tsxStatelessFunctionComponentOverload4.tsx | 2 +- .../jsx/tsxStatelessFunctionComponents1.tsx | 2 +- 21 files changed, 120 insertions(+), 86 deletions(-) diff --git a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt index 6bb91bd6385..aeeceb8652e 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt @@ -2,7 +2,6 @@ tests/cases/conformance/jsx/file.tsx(14,15): error TS2322: Type '{ a: 10; b: "hi Type '{ a: 10; b: "hi"; }' is not assignable to type 'Prop'. Property 'children' is missing in type '{ a: 10; b: "hi"; }'. tests/cases/conformance/jsx/file.tsx(17,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. -tests/cases/conformance/jsx/file.tsx(25,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. tests/cases/conformance/jsx/file.tsx(31,11): error TS2322: Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'IntrinsicAttributes & Prop'. Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. @@ -29,7 +28,7 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi Property 'type' is missing in type 'Element[]'. -==== tests/cases/conformance/jsx/file.tsx (7 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (6 errors) ==== import React = require('react'); interface Prop { @@ -61,8 +60,6 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi } let k1 = - ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. hi hi hi! ; diff --git a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt index 28c550ccda1..0790c09295b 100644 --- a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt +++ b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt @@ -1,18 +1,17 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,24): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. + Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,64): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,24): error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,24): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,43): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,24): error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,25): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,65): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -==== tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx (6 errors) ==== +==== tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx (7 errors) ==== import React = require('react') export interface ClickableProps { @@ -42,15 +41,17 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): err const b0 = {console.log(k)}}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. +!!! error TS2322: Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. const b2 = {console.log(k)}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. !!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. const b3 = ; // goTo has type"home" | "contact" - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. const b4 = ; // goTo has type "home" | "contact" ~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. @@ -58,13 +59,11 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): err export function NoOverload(buttonProps: ButtonProps): JSX.Element { return undefined } const c1 = {console.log(k)}}} extra />; // k has type any - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. export function NoOverload1(linkProps: LinkProps): JSX.Element { return undefined } const d1 = ; // goTo has type "home" | "contact" - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxAttributeResolution3.errors.txt b/tests/baselines/reference/tsxAttributeResolution3.errors.txt index d5517ea31a2..b4ec56c0c46 100644 --- a/tests/baselines/reference/tsxAttributeResolution3.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution3.errors.txt @@ -6,11 +6,9 @@ tests/cases/conformance/jsx/file.tsx(23,8): error TS2322: Type '{ y: number; }' tests/cases/conformance/jsx/file.tsx(31,8): error TS2322: Type '{ x: number; y: number; }' is not assignable to type 'Attribs1'. Types of property 'x' are incompatible. Type 'number' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(35,8): error TS2322: Type '{ x: string; y: number; extra: number; }' is not assignable to type 'Attribs1'. - Property 'extra' does not exist on type 'Attribs1'. -==== tests/cases/conformance/jsx/file.tsx (4 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== declare module JSX { interface Element { } interface IntrinsicElements { @@ -54,12 +52,9 @@ tests/cases/conformance/jsx/file.tsx(35,8): error TS2322: Type '{ x: string; y: !!! error TS2322: Types of property 'x' are incompatible. !!! error TS2322: Type 'number' is not assignable to type 'string'. - // Error + // Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; - ~~~~~~~~~ -!!! error TS2322: Type '{ x: string; y: number; extra: number; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'extra' does not exist on type 'Attribs1'. // OK (spread override) var obj7 = { x: 'foo' }; diff --git a/tests/baselines/reference/tsxAttributeResolution3.js b/tests/baselines/reference/tsxAttributeResolution3.js index c96fd77e284..692fb4ba0b9 100644 --- a/tests/baselines/reference/tsxAttributeResolution3.js +++ b/tests/baselines/reference/tsxAttributeResolution3.js @@ -31,7 +31,7 @@ var obj4 = { x: 32, y: 32 }; var obj5 = { x: 32, y: 32 }; -// Error +// Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; @@ -56,7 +56,7 @@ var obj4 = { x: 32, y: 32 }; // Error var obj5 = { x: 32, y: 32 }; ; -// Error +// Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; ; // OK (spread override) diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt index 0c1ebce61bf..a43c9270642 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt +++ b/tests/baselines/reference/tsxSpreadAttributesResolution12.errors.txt @@ -6,9 +6,13 @@ tests/cases/conformance/jsx/file.tsx(28,25): error TS2322: Type '{ y: true; x: 3 Type '{ y: true; x: 3; overwrite: "hi"; }' is not assignable to type 'Prop'. Types of property 'x' are incompatible. Type '3' is not assignable to type '2'. +tests/cases/conformance/jsx/file.tsx(30,25): error TS2322: Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Prop & { children?: ReactNode; }'. + Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'Prop'. + Types of property 'y' are incompatible. + Type 'true' is not assignable to type 'false'. -==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== import React = require('react'); const obj = {}; @@ -48,4 +52,11 @@ tests/cases/conformance/jsx/file.tsx(28,25): error TS2322: Type '{ y: true; x: 3 !!! error TS2322: Types of property 'x' are incompatible. !!! error TS2322: Type '3' is not assignable to type '2'. let x2 = + let x3 = + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Prop & { children?: ReactNode; }'. +!!! error TS2322: Type '{ y: true; x: 2; overwrite: "hi"; }' is not assignable to type 'Prop'. +!!! error TS2322: Types of property 'y' are incompatible. +!!! error TS2322: Type 'true' is not assignable to type 'false'. + \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution12.js b/tests/baselines/reference/tsxSpreadAttributesResolution12.js index 8551a3f1bac..a68755a7592 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution12.js +++ b/tests/baselines/reference/tsxSpreadAttributesResolution12.js @@ -28,6 +28,8 @@ let anyobj: any; let x = let x1 = let x2 = +let x3 = + //// [file.jsx] @@ -67,3 +69,4 @@ var anyobj; var x = ; var x1 = ; var x2 = ; +var x3 = ; diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt index 57b616124d1..a4314f9718f 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt +++ b/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt @@ -8,9 +8,18 @@ tests/cases/conformance/jsx/file.tsx(19,19): error TS2322: Type '{ x: true; y: t Type '{ x: true; y: true; }' is not assignable to type 'PoisonedProp'. Types of property 'x' are incompatible. Type 'true' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(20,19): error TS2322: Type '{ x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. + Type '{ x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. + Types of property 'x' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(21,20): error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. + Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. + Types of property 'x' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(21,40): error TS2339: Property 'X' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. -==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (6 errors) ==== import React = require('react'); interface PoisonedProp { @@ -42,4 +51,18 @@ tests/cases/conformance/jsx/file.tsx(19,19): error TS2322: Type '{ x: true; y: t !!! error TS2322: Type '{ x: true; y: true; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. !!! error TS2322: Type '{ x: true; y: true; }' is not assignable to type 'PoisonedProp'. !!! error TS2322: Types of property 'x' are incompatible. -!!! error TS2322: Type 'true' is not assignable to type 'string'. \ No newline at end of file +!!! error TS2322: Type 'true' is not assignable to type 'string'. + let w = ; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. +!!! error TS2322: Type '{ x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. +!!! error TS2322: Types of property 'x' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. + let w1 = ; + ~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. +!!! error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. +!!! error TS2322: Types of property 'x' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. + ~~~~~~ +!!! error TS2339: Property 'X' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution2.js b/tests/baselines/reference/tsxSpreadAttributesResolution2.js index 75da8fc2291..ad2af275485 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution2.js +++ b/tests/baselines/reference/tsxSpreadAttributesResolution2.js @@ -17,7 +17,9 @@ const obj = {}; // Error let p = ; let y = ; -let z = ; +let z = ; +let w = ; +let w1 = ; //// [file.jsx] "use strict"; @@ -48,3 +50,5 @@ var obj = {}; var p = ; var y = ; var z = ; +var w = ; +var w1 = ; diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt index 2212d0da025..be7018512f9 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt +++ b/tests/baselines/reference/tsxSpreadAttributesResolution5.errors.txt @@ -2,11 +2,9 @@ tests/cases/conformance/jsx/file.tsx(20,19): error TS2322: Type '{ x: string; y: Type '{ x: string; y: number; }' is not assignable to type 'PoisonedProp'. Types of property 'y' are incompatible. Type 'number' is not assignable to type '2'. -tests/cases/conformance/jsx/file.tsx(33,20): error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== import React = require('react'); interface PoisonedProp { @@ -43,8 +41,5 @@ tests/cases/conformance/jsx/file.tsx(33,20): error TS2322: Type '{ prop1: boolea let o = { prop1: false } - // Error - let e = ; - ~~~~~~ -!!! error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. \ No newline at end of file + // Ok + let e = ; \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution5.js b/tests/baselines/reference/tsxSpreadAttributesResolution5.js index a40139b316e..192f4b78770 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution5.js +++ b/tests/baselines/reference/tsxSpreadAttributesResolution5.js @@ -30,7 +30,7 @@ class EmptyProp extends React.Component<{}, {}> { let o = { prop1: false } -// Error +// Ok let e = ; //// [file.jsx] @@ -76,5 +76,5 @@ var EmptyProp = (function (_super) { var o = { prop1: false }; -// Error +// Ok var e = ; diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt index b59b1dd44f4..c7f1b03f6aa 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt @@ -7,10 +7,7 @@ tests/cases/conformance/jsx/file.tsx(14,22): error TS2322: Type '{ yy1: true; yy Type '{ yy1: true; yy: number; }' is not assignable to type '{ yy: number; yy1: string; }'. Types of property 'yy1' are incompatible. Type 'true' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(15,22): error TS2322: Type '{ extra: string; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. - Property 'extra' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -tests/cases/conformance/jsx/file.tsx(16,22): error TS2322: Type '{ y1: 10000; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. - Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. +tests/cases/conformance/jsx/file.tsx(16,31): error TS2339: Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. tests/cases/conformance/jsx/file.tsx(17,22): error TS2322: Type '{ yy: boolean; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. Type '{ yy: boolean; yy1: string; }' is not assignable to type '{ yy: number; yy1: string; }'. Types of property 'yy' are incompatible. @@ -36,7 +33,7 @@ tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. -==== tests/cases/conformance/jsx/file.tsx (12 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (11 errors) ==== import React = require('react') declare function OneThing(): JSX.Element; declare function OneThing(l: {yy: number, yy1: string}): JSX.Element; @@ -63,14 +60,10 @@ tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; !!! error TS2322: Type '{ yy1: true; yy: number; }' is not assignable to type '{ yy: number; yy1: string; }'. !!! error TS2322: Types of property 'yy1' are incompatible. !!! error TS2322: Type 'true' is not assignable to type 'string'. - const c3 = ; // Extra attribute; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: string; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. + const c3 = ; // This is OK becuase all attribute are spread const c4 = ; // extra property; - ~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ y1: 10000; yy: number; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -!!! error TS2322: Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. + ~~~~~~~~~~ +!!! error TS2339: Property 'y1' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. const c5 = ; // type incompatible; ~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ yy: boolean; yy1: string; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js index 8da2bee37ea..d67466d1271 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.js @@ -13,7 +13,7 @@ let obj2: any; const c0 = ; // extra property; const c1 = ; // missing property; const c2 = ; // type incompatible; -const c3 = ; // Extra attribute; +const c3 = ; // This is OK becuase all attribute are spread const c4 = ; // extra property; const c5 = ; // type incompatible; const c6 = ; // Should error as there is extra attribute that doesn't match any. Current it is not @@ -50,7 +50,7 @@ define(["require", "exports", "react"], function (require, exports, React) { var c0 = ; // extra property; var c1 = ; // missing property; var c2 = ; // type incompatible; - var c3 = ; // Extra attribute; + var c3 = ; // This is OK becuase all attribute are spread var c4 = ; // extra property; var c5 = ; // type incompatible; var c6 = ; // Should error as there is extra attribute that doesn't match any. Current it is not diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt index a7b787c1c18..d2ff4736e61 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt @@ -1,24 +1,31 @@ tests/cases/conformance/jsx/file.tsx(48,24): error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. +tests/cases/conformance/jsx/file.tsx(49,24): error TS2339: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. tests/cases/conformance/jsx/file.tsx(49,24): error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ to: string; onClick: (e: any) => void; children: string; }'. tests/cases/conformance/jsx/file.tsx(50,24): error TS2322: Type '{ onClick: () => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ onClick: () => void; to: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ onClick: () => void; to: string; }'. tests/cases/conformance/jsx/file.tsx(51,24): error TS2322: Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ onClick: (k: MouseEvent) => void; to: string; }'. tests/cases/conformance/jsx/file.tsx(53,24): error TS2322: Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ to: string; onClick(e: any): void; }'. tests/cases/conformance/jsx/file.tsx(54,24): error TS2322: Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ children: 10; onClick(e: any): void; }'. tests/cases/conformance/jsx/file.tsx(55,24): error TS2322: Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ children: "hello"; className: true; onClick(e: any): void; }'. tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type '{ data-format: true; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. Type '{ data-format: true; }' is not assignable to type 'HyphenProps'. Types of property '"data-format"' are incompatible. Type 'true' is not assignable to type 'string'. -==== tests/cases/conformance/jsx/file.tsx (8 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (9 errors) ==== import React = require('react') export interface ClickableProps { @@ -71,30 +78,38 @@ tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type '{ data-format: !!! error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. !!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. const b1 = {}} {...obj0}>Hello world; // extra property; + ~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2339: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ to: string; onClick: (e: any) => void; children: string; }'. const b2 = ; // extra property ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: () => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ onClick: () => void; to: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ onClick: () => void; to: string; }'. const b3 = {}}} />; // extra property ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ onClick: (k: MouseEvent) => void; to: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ onClick: (k: MouseEvent) => void; to: string; }'. const b4 = ; // Should error because Incorrect type; but attributes are any so everything is allowed const b5 = ; // Spread retain method declaration (see GitHub #13365), so now there is an extra attributes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ to: string; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ to: string; onClick(e: any): void; }'. const b6 = ; // incorrect type for optional attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ children: 10; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ children: 10; onClick(e: any): void; }'. const b7 = ; // incorrect type for optional attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ children: "hello"; className: true; onClick(e: any): void; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ children: "hello"; className: true; onClick(e: any): void; }'. const b8 = ; // incorrect type for specified hyphanated name ~~~~~~~~~~~ !!! error TS2322: Type '{ data-format: true; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt index 51e1de2a57e..1f2c00c73d1 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt @@ -14,11 +14,9 @@ tests/cases/conformance/jsx/file.tsx(37,23): error TS2322: Type '{ prop1: true; tests/cases/conformance/jsx/file.tsx(38,24): error TS2322: Type '{ ref: (x: any) => any; }' is not assignable to type 'IntrinsicAttributes'. Property 'ref' does not exist on type 'IntrinsicAttributes'. tests/cases/conformance/jsx/file.tsx(41,16): error TS1005: ',' expected. -tests/cases/conformance/jsx/file.tsx(45,24): error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes'. - Property 'prop1' does not exist on type 'IntrinsicAttributes'. -==== tests/cases/conformance/jsx/file.tsx (8 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (7 errors) ==== function EmptyPropSFC() { return

Default Greeting
; } @@ -85,11 +83,8 @@ tests/cases/conformance/jsx/file.tsx(45,24): error TS2322: Type '{ prop1: boolea !!! error TS1005: ',' expected. } - // Error + // OK as access properties are allow when spread let i2 = - ~~~~~~ -!!! error TS2322: Type '{ prop1: boolean; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes'. let o1: any; // OK diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents1.js b/tests/baselines/reference/tsxStatelessFunctionComponents1.js index d19f1ce1073..6ede59b4420 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents1.js +++ b/tests/baselines/reference/tsxStatelessFunctionComponents1.js @@ -42,7 +42,7 @@ let o = { prop1: true; } -// Error +// OK as access properties are allow when spread let i2 = let o1: any; @@ -93,7 +93,7 @@ var i1 = ; var o = { prop1: true }; -// Error +// OK as access properties are allow when spread var i2 = ; var o1; // OK diff --git a/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx b/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx index 0f968dd0a5c..d63cf8e4acc 100644 --- a/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx +++ b/tests/cases/conformance/jsx/tsxAttributeResolution3.tsx @@ -32,7 +32,7 @@ var obj4 = { x: 32, y: 32 }; var obj5 = { x: 32, y: 32 }; -// Error +// Ok var obj6 = { x: 'ok', y: 32, extra: 100 }; diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx index b5150bd27ff..457a3f29810 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution12.tsx @@ -32,3 +32,5 @@ let anyobj: any; let x = let x1 = let x2 = +let x3 = + diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx index 1d647226ade..7ec1d871189 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx @@ -21,4 +21,6 @@ const obj = {}; // Error let p = ; let y = ; -let z = ; \ No newline at end of file +let z = ; +let w = ; +let w1 = ; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx index e050932b1db..22045c81451 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution5.tsx @@ -34,5 +34,5 @@ class EmptyProp extends React.Component<{}, {}> { let o = { prop1: false } -// Error +// Ok let e = ; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx index 7700fed6902..b96073b4cc0 100644 --- a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx +++ b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentOverload4.tsx @@ -18,7 +18,7 @@ let obj2: any; const c0 = ; // extra property; const c1 = ; // missing property; const c2 = ; // type incompatible; -const c3 = ; // Extra attribute; +const c3 = ; // This is OK becuase all attribute are spread const c4 = ; // extra property; const c5 = ; // type incompatible; const c6 = ; // Should error as there is extra attribute that doesn't match any. Current it is not diff --git a/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx b/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx index 8990cb3c8b0..b486a72ce15 100644 --- a/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx +++ b/tests/cases/conformance/jsx/tsxStatelessFunctionComponents1.tsx @@ -46,7 +46,7 @@ let o = { prop1: true; } -// Error +// OK as access properties are allow when spread let i2 = let o1: any; From e44d419c904440275ef20a52ccbe00bc9b3a8e97 Mon Sep 17 00:00:00 2001 From: Matt Bierner Date: Thu, 4 May 2017 20:04:46 -0700 Subject: [PATCH 086/282] Add Log for When Typings Installer Finishes Updating the Types Registry **Bug** While investigating #15301, I was confused by the typing installer's log `Updating types-registry npm package...`. This was often the last line of the log file, leading me to believe that the types-registry update was still ongoing **Fix** Add an extra log for when the type-registry update completes successfully --- src/server/typingsInstaller/nodeTypingsInstaller.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/server/typingsInstaller/nodeTypingsInstaller.ts b/src/server/typingsInstaller/nodeTypingsInstaller.ts index 895a4e17cc7..1182450ce81 100644 --- a/src/server/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/server/typingsInstaller/nodeTypingsInstaller.ts @@ -96,6 +96,9 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`Updating ${TypesRegistryPackageName} npm package...`); } this.execSync(`${this.npmPath} install ${TypesRegistryPackageName}`, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + if (this.log.isEnabled()) { + this.log.writeLine(`Updated ${TypesRegistryPackageName} npm package`); + } } catch (e) { if (this.log.isEnabled()) { From fec3dc215a79b7b6838ffe354898f722d2d819d8 Mon Sep 17 00:00:00 2001 From: Yui T Date: Thu, 4 May 2017 22:16:23 -0700 Subject: [PATCH 087/282] Address PR --- src/compiler/checker.ts | 4 ++-- ...extuallyTypedStringLiteralsInJsxAttributes02.errors.txt | 5 +---- .../reference/tsxSpreadAttributesResolution2.errors.txt | 7 ++----- .../tsxStatelessFunctionComponentOverload5.errors.txt | 5 +---- 4 files changed, 6 insertions(+), 15 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b90028993ea..f3db3f22bf2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13909,11 +13909,11 @@ namespace ts { error(openingLikeElement, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + const isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); // If sourceAttributesType has spread (e.g the type doesn't have freshness flag) after we check for assignability, we will do another pass to check that // all explicitly specified attributes have correct name corresponding with target (as those will be assignable as spread type allows excess properties) // Note: if the type of these explicitly specified attributes do not match it will be an error during above assignability check. - if (sourceAttributesType !== anyType && !(sourceAttributesType.flags & TypeFlags.FreshLiteral)) { + if (isSourceAttributeTypeAssignableToTarget && sourceAttributesType !== anyType && !(sourceAttributesType.flags & TypeFlags.FreshLiteral)) { for (const attribute of openingLikeElement.attributes.properties) { if (isJsxAttribute(attribute) && !getPropertyOfType(targetAttributesType, attribute.name.text)) { error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); diff --git a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt index 0790c09295b..63686e29419 100644 --- a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt +++ b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt @@ -1,7 +1,6 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,24): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,64): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,24): error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,43): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. @@ -11,7 +10,7 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,65): err tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -==== tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx (7 errors) ==== +==== tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx (6 errors) ==== import React = require('react') export interface ClickableProps { @@ -43,8 +42,6 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): err !!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. !!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. !!! error TS2322: Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. - ~~~~~ -!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. const b2 = {console.log(k)}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt index a4314f9718f..06a0c4bbea6 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt +++ b/tests/baselines/reference/tsxSpreadAttributesResolution2.errors.txt @@ -16,10 +16,9 @@ tests/cases/conformance/jsx/file.tsx(21,20): error TS2322: Type '{ X: "hi"; x: n Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. Types of property 'x' are incompatible. Type 'number' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(21,40): error TS2339: Property 'X' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. -==== tests/cases/conformance/jsx/file.tsx (6 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (5 errors) ==== import React = require('react'); interface PoisonedProp { @@ -63,6 +62,4 @@ tests/cases/conformance/jsx/file.tsx(21,40): error TS2339: Property 'X' does not !!! error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. !!! error TS2322: Type '{ X: "hi"; x: number; y: "2"; }' is not assignable to type 'PoisonedProp'. !!! error TS2322: Types of property 'x' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'string'. - ~~~~~~ -!!! error TS2339: Property 'X' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & PoisonedProp & { children?: ReactNode; }'. \ No newline at end of file +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt index d2ff4736e61..7c5aa3daa36 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt @@ -1,6 +1,5 @@ tests/cases/conformance/jsx/file.tsx(48,24): error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. -tests/cases/conformance/jsx/file.tsx(49,24): error TS2339: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. tests/cases/conformance/jsx/file.tsx(49,24): error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'HyphenProps'. Property '"data-format"' is missing in type '{ to: string; onClick: (e: any) => void; children: string; }'. @@ -25,7 +24,7 @@ tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type '{ data-format: Type 'true' is not assignable to type 'string'. -==== tests/cases/conformance/jsx/file.tsx (9 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (8 errors) ==== import React = require('react') export interface ClickableProps { @@ -78,8 +77,6 @@ tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type '{ data-format: !!! error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. !!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. const b1 = {}} {...obj0}>Hello world; // extra property; - ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2339: Property 'onClick' does not exist on type 'IntrinsicAttributes & HyphenProps'. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. !!! error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'HyphenProps'. From 5b972b44ff419c00943b0b3e1559d3e0c8e0cdb2 Mon Sep 17 00:00:00 2001 From: Yui T Date: Fri, 5 May 2017 08:47:52 -0700 Subject: [PATCH 088/282] Add tests and baselines --- .../reference/checkJsxChildrenProperty12.js | 60 ++++++++++++++++++ .../checkJsxChildrenProperty12.symbols | 59 ++++++++++++++++++ .../checkJsxChildrenProperty12.types | 62 +++++++++++++++++++ .../tsxSpreadAttributesResolution13.js | 36 +++++++++++ .../tsxSpreadAttributesResolution13.symbols | 47 ++++++++++++++ .../tsxSpreadAttributesResolution13.types | 53 ++++++++++++++++ ...tsxSpreadAttributesResolution14.errors.txt | 29 +++++++++ .../tsxSpreadAttributesResolution14.js | 39 ++++++++++++ .../tsxSpreadAttributesResolution15.js | 38 ++++++++++++ .../tsxSpreadAttributesResolution15.symbols | 55 ++++++++++++++++ .../tsxSpreadAttributesResolution15.types | 61 ++++++++++++++++++ .../jsx/checkJsxChildrenProperty12.tsx | 28 +++++++++ .../jsx/tsxSpreadAttributesResolution13.tsx | 27 ++++++++ .../jsx/tsxSpreadAttributesResolution14.tsx | 28 +++++++++ .../jsx/tsxSpreadAttributesResolution15.tsx | 29 +++++++++ 15 files changed, 651 insertions(+) create mode 100644 tests/baselines/reference/checkJsxChildrenProperty12.js create mode 100644 tests/baselines/reference/checkJsxChildrenProperty12.symbols create mode 100644 tests/baselines/reference/checkJsxChildrenProperty12.types create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution13.js create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution13.symbols create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution13.types create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution14.errors.txt create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution14.js create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution15.js create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution15.symbols create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution15.types create mode 100644 tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx create mode 100644 tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx create mode 100644 tests/cases/conformance/jsx/tsxSpreadAttributesResolution14.tsx create mode 100644 tests/cases/conformance/jsx/tsxSpreadAttributesResolution15.tsx diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.js b/tests/baselines/reference/checkJsxChildrenProperty12.js new file mode 100644 index 00000000000..fcb3edf423d --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.js @@ -0,0 +1,60 @@ +//// [file.tsx] +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + return + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} + + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var Button = (function (_super) { + __extends(Button, _super); + function Button() { + return _super !== null && _super.apply(this, arguments) || this; + } + Button.prototype.render = function () { + return ; + }; + return Button; +}(React.Component)); +var InnerButton = (function (_super) { + __extends(InnerButton, _super); + function InnerButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + InnerButton.prototype.render = function () { + return (); + }; + return InnerButton; +}(React.Component)); diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.symbols b/tests/baselines/reference/checkJsxChildrenProperty12.symbols new file mode 100644 index 00000000000..7b45ad96cf4 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +interface ButtonProp { +>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32)) + + a: number, +>a : Symbol(ButtonProp.a, Decl(file.tsx, 2, 22)) + + b: string, +>b : Symbol(ButtonProp.b, Decl(file.tsx, 3, 14)) + + children: Button; +>children : Symbol(ButtonProp.children, Decl(file.tsx, 4, 14)) +>Button : Symbol(Button, Decl(file.tsx, 6, 1)) +} + +class Button extends React.Component { +>Button : Symbol(Button, Decl(file.tsx, 6, 1)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32)) + + render() { +>render : Symbol(Button.render, Decl(file.tsx, 8, 55)) + + return +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 16, 1)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(Button, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + } +} + +interface InnerButtonProp { +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 12, 1)) + + a: number +>a : Symbol(InnerButtonProp.a, Decl(file.tsx, 14, 27)) +} + +class InnerButton extends React.Component { +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 16, 1)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 12, 1)) + + render() { +>render : Symbol(InnerButton.render, Decl(file.tsx, 18, 65)) + + return (); +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) + } +} + diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.types b/tests/baselines/reference/checkJsxChildrenProperty12.types new file mode 100644 index 00000000000..cc2d2300828 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.types @@ -0,0 +1,62 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +interface ButtonProp { +>ButtonProp : ButtonProp + + a: number, +>a : number + + b: string, +>b : string + + children: Button; +>children : Button +>Button : Button +} + +class Button extends React.Component { +>Button : Button +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>ButtonProp : ButtonProp + + render() { +>render : () => JSX.Element + + return +> : JSX.Element +>InnerButton : typeof InnerButton +>this.props : ButtonProp & { children?: React.ReactNode; } +>this : this +>props : ButtonProp & { children?: React.ReactNode; } + } +} + +interface InnerButtonProp { +>InnerButtonProp : InnerButtonProp + + a: number +>a : number +} + +class InnerButton extends React.Component { +>InnerButton : InnerButton +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>InnerButtonProp : InnerButtonProp + + render() { +>render : () => JSX.Element + + return (); +>() : JSX.Element +> : JSX.Element +>button : any +>button : any + } +} + diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.js b/tests/baselines/reference/tsxSpreadAttributesResolution13.js new file mode 100644 index 00000000000..f1626414397 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.js @@ -0,0 +1,36 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + + ); +} + +interface AnotherComponentProps { + property1: string; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + return (); +} +exports["default"] = Component; +function AnotherComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols b/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols new file mode 100644 index 00000000000..1923c39c85a --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols @@ -0,0 +1,47 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +interface ComponentProps { +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + property1: string; +>property1 : Symbol(ComponentProps.property1, Decl(file.tsx, 2, 26)) + + property2: number; +>property2 : Symbol(ComponentProps.property2, Decl(file.tsx, 3, 22)) +} + +export default function Component(props: ComponentProps) { +>Component : Symbol(Component, Decl(file.tsx, 5, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + return ( + +>AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 15, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) + + ); +} + +interface AnotherComponentProps { +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) + + property1: string; +>property1 : Symbol(AnotherComponentProps.property1, Decl(file.tsx, 13, 33)) +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { +>AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 15, 1)) +>property1 : Symbol(property1, Decl(file.tsx, 17, 27)) +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) + + return ( + {property1} +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) +>property1 : Symbol(property1, Decl(file.tsx, 17, 27)) +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) + + ); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.types b/tests/baselines/reference/tsxSpreadAttributesResolution13.types new file mode 100644 index 00000000000..0c231dddece --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.types @@ -0,0 +1,53 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +interface ComponentProps { +>ComponentProps : ComponentProps + + property1: string; +>property1 : string + + property2: number; +>property2 : number +} + +export default function Component(props: ComponentProps) { +>Component : (props: ComponentProps) => JSX.Element +>props : ComponentProps +>ComponentProps : ComponentProps + + return ( +>( ) : JSX.Element + + +> : JSX.Element +>AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element +>props : ComponentProps + + ); +} + +interface AnotherComponentProps { +>AnotherComponentProps : AnotherComponentProps + + property1: string; +>property1 : string +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { +>AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element +>property1 : string +>AnotherComponentProps : AnotherComponentProps + + return ( +>( {property1} ) : JSX.Element + + {property1} +>{property1} : JSX.Element +>span : any +>property1 : string +>span : any + + ); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution14.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution14.errors.txt new file mode 100644 index 00000000000..536d2e75f84 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution14.errors.txt @@ -0,0 +1,29 @@ +tests/cases/conformance/jsx/file.tsx(11,38): error TS2339: Property 'Property1' does not exist on type 'IntrinsicAttributes & AnotherComponentProps'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + interface ComponentProps { + property1: string; + property2: number; + } + + export default function Component(props: ComponentProps) { + return ( + // Error extra property + + ~~~~~~~~~ +!!! error TS2339: Property 'Property1' does not exist on type 'IntrinsicAttributes & AnotherComponentProps'. + ); + } + + interface AnotherComponentProps { + property1: string; + } + + function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution14.js b/tests/baselines/reference/tsxSpreadAttributesResolution14.js new file mode 100644 index 00000000000..d04c9cd6d99 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution14.js @@ -0,0 +1,39 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error extra property + + ); +} + +interface AnotherComponentProps { + property1: string; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + return ( + // Error extra property + ); +} +exports["default"] = Component; +function AnotherComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution15.js b/tests/baselines/reference/tsxSpreadAttributesResolution15.js new file mode 100644 index 00000000000..41302f22a61 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution15.js @@ -0,0 +1,38 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + return (); +} +exports["default"] = Component; +function AnotherComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution15.symbols b/tests/baselines/reference/tsxSpreadAttributesResolution15.symbols new file mode 100644 index 00000000000..00e10954821 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution15.symbols @@ -0,0 +1,55 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +interface ComponentProps { +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + property1: string; +>property1 : Symbol(ComponentProps.property1, Decl(file.tsx, 2, 26)) + + property2: number; +>property2 : Symbol(ComponentProps.property2, Decl(file.tsx, 3, 22)) +} + +export default function Component(props: ComponentProps) { +>Component : Symbol(Component, Decl(file.tsx, 5, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) + + return ( + +>AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 17, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>property2 : Symbol(property2, Decl(file.tsx, 9, 36)) +>AnotherProperty1 : Symbol(AnotherProperty1, Decl(file.tsx, 9, 46)) + + ); +} + +interface AnotherComponentProps { +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) + + property1: string; +>property1 : Symbol(AnotherComponentProps.property1, Decl(file.tsx, 13, 33)) + + AnotherProperty1: string; +>AnotherProperty1 : Symbol(AnotherComponentProps.AnotherProperty1, Decl(file.tsx, 14, 22)) + + property2: boolean; +>property2 : Symbol(AnotherComponentProps.property2, Decl(file.tsx, 15, 29)) +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { +>AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 17, 1)) +>property1 : Symbol(property1, Decl(file.tsx, 19, 27)) +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) + + return ( + {property1} +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) +>property1 : Symbol(property1, Decl(file.tsx, 19, 27)) +>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) + + ); +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution15.types b/tests/baselines/reference/tsxSpreadAttributesResolution15.types new file mode 100644 index 00000000000..dbcb6541a03 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution15.types @@ -0,0 +1,61 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +interface ComponentProps { +>ComponentProps : ComponentProps + + property1: string; +>property1 : string + + property2: number; +>property2 : number +} + +export default function Component(props: ComponentProps) { +>Component : (props: ComponentProps) => JSX.Element +>props : ComponentProps +>ComponentProps : ComponentProps + + return ( +>( ) : JSX.Element + + +> : JSX.Element +>AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element +>props : ComponentProps +>property2 : true +>AnotherProperty1 : string + + ); +} + +interface AnotherComponentProps { +>AnotherComponentProps : AnotherComponentProps + + property1: string; +>property1 : string + + AnotherProperty1: string; +>AnotherProperty1 : string + + property2: boolean; +>property2 : boolean +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { +>AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element +>property1 : string +>AnotherComponentProps : AnotherComponentProps + + return ( +>( {property1} ) : JSX.Element + + {property1} +>{property1} : JSX.Element +>span : any +>property1 : string +>span : any + + ); +} diff --git a/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx b/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx new file mode 100644 index 00000000000..ba42e9e83d4 --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx @@ -0,0 +1,28 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + return + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx new file mode 100644 index 00000000000..dda315b0826 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx @@ -0,0 +1,27 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + + ); +} + +interface AnotherComponentProps { + property1: string; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution14.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution14.tsx new file mode 100644 index 00000000000..b9edcc8ab75 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution14.tsx @@ -0,0 +1,28 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error extra property + + ); +} + +interface AnotherComponentProps { + property1: string; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution15.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution15.tsx new file mode 100644 index 00000000000..5ede01c0eab --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution15.tsx @@ -0,0 +1,29 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file From d36175b1e8741c1a31e3d2bc545dd8a1b2bc6210 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 5 May 2017 08:51:18 -0700 Subject: [PATCH 089/282] Remove some redundant code in createJsxAttributesTypeFromAttributesProperty --- src/compiler/checker.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 84ff54391de..b717a4d196c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13293,19 +13293,15 @@ namespace ts { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = createMap(); } attributesArray = getPropertiesOfType(spread); } attributesTable = createMap(); - if (attributesArray) { - forEach(attributesArray, (attr) => { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); - } - }); + for (const attr of attributesArray) { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } } } From d94d4906471f9971a9a3f51239bedd92ed67c6c9 Mon Sep 17 00:00:00 2001 From: Yui T Date: Fri, 5 May 2017 10:05:50 -0700 Subject: [PATCH 090/282] Updates tests and baselines --- .../reference/checkJsxChildrenProperty12.js | 20 +++++- .../checkJsxChildrenProperty12.symbols | 35 ++++++++-- .../checkJsxChildrenProperty12.types | 26 +++++++- .../checkJsxChildrenProperty13.errors.txt | 33 ++++++++++ .../reference/checkJsxChildrenProperty13.js | 66 +++++++++++++++++++ .../tsxSpreadAttributesResolution13.js | 24 +++++-- .../tsxSpreadAttributesResolution13.symbols | 35 ++++++---- .../tsxSpreadAttributesResolution13.types | 31 ++++++--- ...tsxSpreadAttributesResolution16.errors.txt | 35 ++++++++++ .../tsxSpreadAttributesResolution16.js | 41 ++++++++++++ .../jsx/checkJsxChildrenProperty12.tsx | 10 ++- .../jsx/checkJsxChildrenProperty13.tsx | 31 +++++++++ .../jsx/tsxSpreadAttributesResolution13.tsx | 14 ++-- .../jsx/tsxSpreadAttributesResolution16.tsx | 30 +++++++++ 14 files changed, 391 insertions(+), 40 deletions(-) create mode 100644 tests/baselines/reference/checkJsxChildrenProperty13.errors.txt create mode 100644 tests/baselines/reference/checkJsxChildrenProperty13.js create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution16.errors.txt create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution16.js create mode 100644 tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx create mode 100644 tests/cases/conformance/jsx/tsxSpreadAttributesResolution16.tsx diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.js b/tests/baselines/reference/checkJsxChildrenProperty12.js index fcb3edf423d..0030d87483f 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty12.js +++ b/tests/baselines/reference/checkJsxChildrenProperty12.js @@ -9,7 +9,15 @@ interface ButtonProp { class Button extends React.Component { render() { - return + let condition: boolean; + if (condition) { + return + } + else { + return ( +
Hello World
+
); + } } } @@ -44,7 +52,15 @@ var Button = (function (_super) { return _super !== null && _super.apply(this, arguments) || this; } Button.prototype.render = function () { - return ; + var condition; + if (condition) { + return ; + } + else { + return ( +
Hello World
+
); + } }; return Button; }(React.Component)); diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.symbols b/tests/baselines/reference/checkJsxChildrenProperty12.symbols index 7b45ad96cf4..ccfb4b18875 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty12.symbols +++ b/tests/baselines/reference/checkJsxChildrenProperty12.symbols @@ -26,30 +26,51 @@ class Button extends React.Component { render() { >render : Symbol(Button.render, Decl(file.tsx, 8, 55)) - return ->InnerButton : Symbol(InnerButton, Decl(file.tsx, 16, 1)) + let condition: boolean; +>condition : Symbol(condition, Decl(file.tsx, 10, 5)) + + if (condition) { +>condition : Symbol(condition, Decl(file.tsx, 10, 5)) + + return +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) >this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) >this : Symbol(Button, Decl(file.tsx, 6, 1)) >props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + } + else { + return ( +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(Button, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + +
Hello World
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
); +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) + } } } interface InnerButtonProp { ->InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 12, 1)) +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1)) a: number ->a : Symbol(InnerButtonProp.a, Decl(file.tsx, 14, 27)) +>a : Symbol(InnerButtonProp.a, Decl(file.tsx, 22, 27)) } class InnerButton extends React.Component { ->InnerButton : Symbol(InnerButton, Decl(file.tsx, 16, 1)) +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) >React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) >React : Symbol(React, Decl(file.tsx, 0, 0)) >Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) ->InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 12, 1)) +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1)) render() { ->render : Symbol(InnerButton.render, Decl(file.tsx, 18, 65)) +>render : Symbol(InnerButton.render, Decl(file.tsx, 26, 65)) return (); >button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.types b/tests/baselines/reference/checkJsxChildrenProperty12.types index cc2d2300828..93a7d0f9be1 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty12.types +++ b/tests/baselines/reference/checkJsxChildrenProperty12.types @@ -26,12 +26,36 @@ class Button extends React.Component { render() { >render : () => JSX.Element - return + let condition: boolean; +>condition : boolean + + if (condition) { +>condition : boolean + + return > : JSX.Element >InnerButton : typeof InnerButton >this.props : ButtonProp & { children?: React.ReactNode; } >this : this >props : ButtonProp & { children?: React.ReactNode; } + } + else { + return ( +>(
Hello World
) : JSX.Element +>
Hello World
: JSX.Element +>InnerButton : typeof InnerButton +>this.props : ButtonProp & { children?: React.ReactNode; } +>this : this +>props : ButtonProp & { children?: React.ReactNode; } + +
Hello World
+>
Hello World
: JSX.Element +>div : any +>div : any + +
); +>InnerButton : typeof InnerButton + } } } diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt new file mode 100644 index 00000000000..c926980cab1 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt @@ -0,0 +1,33 @@ +tests/cases/conformance/jsx/file.tsx(12,30): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + interface ButtonProp { + a: number, + b: string, + children: Button; + } + + class Button extends React.Component { + render() { + // Error children are specified twice + return ( + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. +
Hello World
+
); + } + } + + interface InnerButtonProp { + a: number + } + + class InnerButton extends React.Component { + render() { + return (); + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.js b/tests/baselines/reference/checkJsxChildrenProperty13.js new file mode 100644 index 00000000000..8947e6b211f --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty13.js @@ -0,0 +1,66 @@ +//// [file.tsx] +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + // Error children are specified twice + return ( +
Hello World
+
); + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} + + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var Button = (function (_super) { + __extends(Button, _super); + function Button() { + return _super !== null && _super.apply(this, arguments) || this; + } + Button.prototype.render = function () { + // Error children are specified twice + return ( +
Hello World
+
); + }; + return Button; +}(React.Component)); +var InnerButton = (function (_super) { + __extends(InnerButton, _super); + function InnerButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + InnerButton.prototype.render = function () { + return (); + }; + return InnerButton; +}(React.Component)); diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.js b/tests/baselines/reference/tsxSpreadAttributesResolution13.js index f1626414397..8227f3d6399 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution13.js +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.js @@ -7,16 +7,22 @@ interface ComponentProps { } export default function Component(props: ComponentProps) { - return ( - - ); + let condition1: boolean; + if (condition1) { + return ( + + ); + } + else { + return (); + } } interface AnotherComponentProps { property1: string; } -function AnotherComponent({ property1 }: AnotherComponentProps) { +function ChildComponent({ property1 }: AnotherComponentProps) { return ( {property1} ); @@ -27,10 +33,16 @@ function AnotherComponent({ property1 }: AnotherComponentProps) { exports.__esModule = true; var React = require("react"); function Component(props) { - return (); + var condition1; + if (condition1) { + return (); + } + else { + return (); + } } exports["default"] = Component; -function AnotherComponent(_a) { +function ChildComponent(_a) { var property1 = _a.property1; return ({property1}); } diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols b/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols index 1923c39c85a..2e146225792 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.symbols @@ -17,30 +17,43 @@ export default function Component(props: ComponentProps) { >props : Symbol(props, Decl(file.tsx, 7, 34)) >ComponentProps : Symbol(ComponentProps, Decl(file.tsx, 0, 32)) - return ( - ->AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 15, 1)) + let condition1: boolean; +>condition1 : Symbol(condition1, Decl(file.tsx, 8, 7)) + + if (condition1) { +>condition1 : Symbol(condition1, Decl(file.tsx, 8, 7)) + + return ( + +>ChildComponent : Symbol(ChildComponent, Decl(file.tsx, 21, 1)) >props : Symbol(props, Decl(file.tsx, 7, 34)) - ); + ); + } + else { + return (); +>ChildComponent : Symbol(ChildComponent, Decl(file.tsx, 21, 1)) +>props : Symbol(props, Decl(file.tsx, 7, 34)) +>property1 : Symbol(property1, Decl(file.tsx, 15, 42)) + } } interface AnotherComponentProps { ->AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 17, 1)) property1: string; ->property1 : Symbol(AnotherComponentProps.property1, Decl(file.tsx, 13, 33)) +>property1 : Symbol(AnotherComponentProps.property1, Decl(file.tsx, 19, 33)) } -function AnotherComponent({ property1 }: AnotherComponentProps) { ->AnotherComponent : Symbol(AnotherComponent, Decl(file.tsx, 15, 1)) ->property1 : Symbol(property1, Decl(file.tsx, 17, 27)) ->AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 11, 1)) +function ChildComponent({ property1 }: AnotherComponentProps) { +>ChildComponent : Symbol(ChildComponent, Decl(file.tsx, 21, 1)) +>property1 : Symbol(property1, Decl(file.tsx, 23, 25)) +>AnotherComponentProps : Symbol(AnotherComponentProps, Decl(file.tsx, 17, 1)) return ( {property1} >span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) ->property1 : Symbol(property1, Decl(file.tsx, 17, 27)) +>property1 : Symbol(property1, Decl(file.tsx, 23, 25)) >span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51)) ); diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.types b/tests/baselines/reference/tsxSpreadAttributesResolution13.types index 0c231dddece..5b5ada68613 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution13.types +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.types @@ -17,15 +17,30 @@ export default function Component(props: ComponentProps) { >props : ComponentProps >ComponentProps : ComponentProps - return ( ->( ) : JSX.Element + let condition1: boolean; +>condition1 : boolean - -> : JSX.Element ->AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element + if (condition1) { +>condition1 : boolean + + return ( +>( ) : JSX.Element + + +> : JSX.Element +>ChildComponent : ({property1}: AnotherComponentProps) => JSX.Element >props : ComponentProps - ); + ); + } + else { + return (); +>() : JSX.Element +> : JSX.Element +>ChildComponent : ({property1}: AnotherComponentProps) => JSX.Element +>props : ComponentProps +>property1 : string + } } interface AnotherComponentProps { @@ -35,8 +50,8 @@ interface AnotherComponentProps { >property1 : string } -function AnotherComponent({ property1 }: AnotherComponentProps) { ->AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element +function ChildComponent({ property1 }: AnotherComponentProps) { +>ChildComponent : ({property1}: AnotherComponentProps) => JSX.Element >property1 : string >AnotherComponentProps : AnotherComponentProps diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution16.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution16.errors.txt new file mode 100644 index 00000000000..ddfb9c1c6cf --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution16.errors.txt @@ -0,0 +1,35 @@ +tests/cases/conformance/jsx/file.tsx(11,27): error TS2322: Type '{ property1: string; property2: number; }' is not assignable to type 'IntrinsicAttributes & AnotherComponentProps'. + Type '{ property1: string; property2: number; }' is not assignable to type 'AnotherComponentProps'. + Property 'AnotherProperty1' is missing in type '{ property1: string; property2: number; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + interface ComponentProps { + property1: string; + property2: number; + } + + export default function Component(props: ComponentProps) { + return ( + // Error: missing property + + ~~~~~~~~~~ +!!! error TS2322: Type '{ property1: string; property2: number; }' is not assignable to type 'IntrinsicAttributes & AnotherComponentProps'. +!!! error TS2322: Type '{ property1: string; property2: number; }' is not assignable to type 'AnotherComponentProps'. +!!! error TS2322: Property 'AnotherProperty1' is missing in type '{ property1: string; property2: number; }'. + ); + } + + interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; + } + + function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution16.js b/tests/baselines/reference/tsxSpreadAttributesResolution16.js new file mode 100644 index 00000000000..ad0d4b01885 --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution16.js @@ -0,0 +1,41 @@ +//// [file.tsx] +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error: missing property + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +function Component(props) { + return ( + // Error: missing property + ); +} +exports["default"] = Component; +function AnotherComponent(_a) { + var property1 = _a.property1; + return ({property1}); +} diff --git a/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx b/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx index ba42e9e83d4..e49b196b8f8 100644 --- a/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx +++ b/tests/cases/conformance/jsx/checkJsxChildrenProperty12.tsx @@ -13,7 +13,15 @@ interface ButtonProp { class Button extends React.Component { render() { - return + let condition: boolean; + if (condition) { + return + } + else { + return ( +
Hello World
+
); + } } } diff --git a/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx b/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx new file mode 100644 index 00000000000..1584bf43159 --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx @@ -0,0 +1,31 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + // Error children are specified twice + return ( +
Hello World
+
); + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx index dda315b0826..b665654514c 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution13.tsx @@ -11,16 +11,22 @@ interface ComponentProps { } export default function Component(props: ComponentProps) { - return ( - - ); + let condition1: boolean; + if (condition1) { + return ( + + ); + } + else { + return (); + } } interface AnotherComponentProps { property1: string; } -function AnotherComponent({ property1 }: AnotherComponentProps) { +function ChildComponent({ property1 }: AnotherComponentProps) { return ( {property1} ); diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution16.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution16.tsx new file mode 100644 index 00000000000..98616661857 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution16.tsx @@ -0,0 +1,30 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ComponentProps { + property1: string; + property2: number; +} + +export default function Component(props: ComponentProps) { + return ( + // Error: missing property + + ); +} + +interface AnotherComponentProps { + property1: string; + AnotherProperty1: string; + property2: boolean; +} + +function AnotherComponent({ property1 }: AnotherComponentProps) { + return ( + {property1} + ); +} \ No newline at end of file From c0adf99f3510092ea190b34d7bdb5526f5187e6b Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 10:54:53 -0700 Subject: [PATCH 091/282] Add aliasing test --- .../codeFixClassImplementInterfaceMemberTypeAlias.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts new file mode 100644 index 00000000000..eab4c80c786 --- /dev/null +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts @@ -0,0 +1,12 @@ +/// + +//// type MyType = [string, number]; +//// interface I { test(a: MyType): void; } +//// class C implements I {[| |]} + +verify.rangeAfterCodeFix(` + test(a: MyType): void { + throw new Error("Method not implemented."); + } +`); + From 1774c67afaa79abb0cba5b36fbf16bb20c7d2e3a Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 11:00:00 -0700 Subject: [PATCH 092/282] parens and this param for function type --- src/compiler/checker.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fc067d63d59..6ee3377d88a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2406,7 +2406,7 @@ namespace ts { return createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (context.checkAlias && type.aliasSymbol) { + if (!context.InTypeAlias && context.checkAlias && type.aliasSymbol) { const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, context); const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, /*addInElementTypeFlag*/ false); return createTypeReferenceNode(name, typeArgumentNodes); @@ -2546,8 +2546,11 @@ namespace ts { if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; - shouldAddParenthesisAroundFunctionType(signature, context); - return signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); + const functionTypeNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); + return shouldAddParenthesisAroundFunctionType(signature, context) ? + createParenthesizedTypeNode(functionTypeNode) : + functionTypeNode; + } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { const signature = resolved.constructSignatures[0]; @@ -2564,7 +2567,7 @@ namespace ts { function shouldAddParenthesisAroundFunctionType(callSignature: Signature, context: NodeBuilderContext) { - if (context.InElementType) { + if (InElementType) { return true; } else if (context.InFirstTypeArgument) { @@ -2727,6 +2730,10 @@ namespace ts { const typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter, context)); const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter, context)); + if (signature.thisParameter) { + const thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } let returnTypeNode: TypeNode; if (signature.typePredicate) { const typePredicate = signature.typePredicate; From b3d793608d8525b2dc3ee1f2a403bf733ba6d102 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 27 Apr 2017 15:46:07 -0700 Subject: [PATCH 093/282] Completion list for a class extending another class should contain members from base class Handles #7158 --- src/compiler/checker.ts | 23 --- src/compiler/utilities.ts | 23 +++ src/services/completions.ts | 92 +++++++++++- .../completionEntryForClassMembers.ts | 142 ++++++++++++++++++ .../completionListInNamedClassExpression.ts | 4 +- ...ListInNamedClassExpressionWithShadowing.ts | 8 +- .../completionListIsGlobalCompletion.ts | 2 +- ...pletionListWithModulesInsideModuleScope.ts | 41 ++--- ...etionListWithModulesOutsideModuleScope2.ts | 35 ++++- 9 files changed, 313 insertions(+), 57 deletions(-) create mode 100644 tests/cases/fourslash/completionEntryForClassMembers.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 84ff54391de..a4470a15ea3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -679,10 +679,6 @@ namespace ts { return type.flags & TypeFlags.Object ? (type).objectFlags : 0; } - function getCheckFlags(symbol: Symbol): CheckFlags { - return symbol.flags & SymbolFlags.Transient ? (symbol).checkFlags : 0; - } - function isGlobalSourceFile(node: Node) { return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node); } @@ -13928,25 +13924,6 @@ namespace ts { return s.valueDeclaration ? s.valueDeclaration.kind : SyntaxKind.PropertyDeclaration; } - function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags { - if (s.valueDeclaration) { - const flags = getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier; - } - if (getCheckFlags(s) & CheckFlags.Synthetic) { - const checkFlags = (s).checkFlags; - const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private : - checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public : - ModifierFlags.Protected; - const staticModifier = checkFlags & CheckFlags.ContainsStatic ? ModifierFlags.Static : 0; - return accessModifier | staticModifier; - } - if (s.flags & SymbolFlags.Prototype) { - return ModifierFlags.Public | ModifierFlags.Static; - } - return 0; - } - function getDeclarationNodeFlagsFromSymbol(s: Symbol): NodeFlags { return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : 0; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index f1b181a03b0..f341e912ccc 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4200,6 +4200,29 @@ namespace ts { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); } + + export function getCheckFlags(symbol: Symbol): CheckFlags { + return symbol.flags & SymbolFlags.Transient ? (symbol).checkFlags : 0; + } + + export function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags { + if (s.valueDeclaration) { + const flags = getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier; + } + if (getCheckFlags(s) & CheckFlags.Synthetic) { + const checkFlags = (s).checkFlags; + const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private : + checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public : + ModifierFlags.Protected; + const staticModifier = checkFlags & CheckFlags.ContainsStatic ? ModifierFlags.Static : 0; + return accessModifier | staticModifier; + } + if (s.flags & SymbolFlags.Prototype) { + return ModifierFlags.Public | ModifierFlags.Static; + } + return 0; + } } namespace ts { diff --git a/src/services/completions.ts b/src/services/completions.ts index 6ac3762b4c7..44915a958c2 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -18,7 +18,7 @@ namespace ts.Completions { return undefined; } - const { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, requestJsDocTagName, requestJsDocTag } = completionData; + const { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, requestJsDocTagName, requestJsDocTag, hasFilteredClassMemberKeywords } = completionData; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion @@ -52,7 +52,7 @@ namespace ts.Completions { sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } @@ -60,8 +60,11 @@ namespace ts.Completions { getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } + if (hasFilteredClassMemberKeywords) { + addRange(entries, classMemberKeywordCompletions); + } // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { addRange(entries, keywordCompletions); } @@ -406,7 +409,7 @@ namespace ts.Completions { } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName, requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName, requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { @@ -505,6 +508,7 @@ namespace ts.Completions { let isGlobalCompletion = false; let isMemberCompletion: boolean; let isNewIdentifierLocation: boolean; + let hasFilteredClassMemberKeywords = false; let symbols: Symbol[] = []; if (isRightOfDot) { @@ -542,7 +546,7 @@ namespace ts.Completions { log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); - return { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName, requestJsDocTag }; + return { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName, requestJsDocTag, hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols(): void { // Right of dot member completion list @@ -599,6 +603,7 @@ namespace ts.Completions { function tryGetGlobalSymbols(): boolean { let objectLikeContainer: ObjectLiteralExpression | BindingPattern; let namedImportsOrExports: NamedImportsOrExports; + let classLikeContainer: ClassLikeDeclaration; let jsxContainer: JsxOpeningLikeElement; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { @@ -611,6 +616,11 @@ namespace ts.Completions { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + return tryGetClassLikeCompletionSymbols(classLikeContainer); + } + if (jsxContainer = tryGetContainingJsxElement(contextToken)) { let attrsType: Type; if ((jsxContainer.kind === SyntaxKind.JsxSelfClosingElement) || (jsxContainer.kind === SyntaxKind.JsxOpeningElement)) { @@ -913,6 +923,31 @@ namespace ts.Completions { return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetClassLikeCompletionSymbols(classLikeDeclaration: ClassLikeDeclaration): boolean { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + + const baseTypeNode = getClassExtendsHeritageClauseElement(classLikeDeclaration); + if (baseTypeNode) { + const baseType = typeChecker.getTypeAtLocation(baseTypeNode); + // List of property symbols of base type that are not private + symbols = filter(typeChecker.getPropertiesOfType(baseType), + baseProperty => !(getDeclarationModifierFlagsFromSymbol(baseProperty) & ModifierFlags.Private)); + } + + return true; + } + /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -953,6 +988,38 @@ namespace ts.Completions { return undefined; } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken: Node): ClassLikeDeclaration { + if (contextToken) { + switch (contextToken.kind) { + case SyntaxKind.OpenBraceToken: // class c { | + if (isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + + // class c {getValue(): number; | } + case SyntaxKind.CommaToken: + case SyntaxKind.SemicolonToken: + // class c { method() { } | } + case SyntaxKind.CloseBraceToken: + if (isClassLike(location)) { + return location; + } + break; + } + } + + // class c { method() { } | method2() { } } + if (location && location.kind === SyntaxKind.SyntaxList && isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } + function tryGetContainingJsxElement(contextToken: Node): JsxOpeningLikeElement { if (contextToken) { const parent = contextToken.parent; @@ -1306,6 +1373,21 @@ namespace ts.Completions { }); } + const classMemberKeywordCompletions = filter(keywordCompletions, entry => { + switch (stringToToken(entry.name)) { + case SyntaxKind.PublicKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.AbstractKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.ConstructorKeyword: + case SyntaxKind.ReadonlyKeyword: + case SyntaxKind.GetKeyword: + case SyntaxKind.SetKeyword: + return true; + } + }); + function isEqualityExpression(node: Node): node is BinaryExpression { return isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts new file mode 100644 index 00000000000..da1051e784a --- /dev/null +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -0,0 +1,142 @@ +/// + +////abstract class B { +//// abstract getValue(): number; +//// /*abstractClass*/ +////} +////class C extends B { +//// /*classThatIsEmptyAndExtendingAnotherClass*/ +////} +////class D extends B { +//// /*classThatHasAlreadyImplementedAnotherClassMethod*/ +//// getValue() { +//// return 10; +//// } +//// /*classThatHasAlreadyImplementedAnotherClassMethodAfterMethod*/ +////} +////class E { +//// /*classThatDoesNotExtendAnotherClass*/ +////} +////class F extends B { +//// public /*classThatHasWrittenPublicKeyword*/ +////} +////class G extends B { +//// static /*classElementContainingStatic*/ +////} +////class H extends B { +//// prop/*classThatStartedWritingIdentifier*/ +////} +////class I extends B { +//// prop0: number +//// /*propDeclarationWithoutSemicolon*/ +//// prop: number; +//// /*propDeclarationWithSemicolon*/ +//// prop1 = 10; +//// /*propAssignmentWithSemicolon*/ +//// prop2 = 10 +//// /*propAssignmentWithoutSemicolon*/ +//// method(): number +//// /*methodSignatureWithoutSemicolon*/ +//// method2(): number; +//// /*methodSignatureWithSemicolon*/ +//// method3() { +//// /*InsideMethod*/ +//// } +//// /*methodImplementation*/ +//// get c() +//// /*accessorSignatureWithoutSemicolon*/ +//// set c() +//// { +//// } +//// /*accessorSignatureImplementation*/ +////} +////class J extends B { +//// get /*classThatHasWrittenGetKeyword*/ +////} +////class K extends B { +//// set /*classThatHasWrittenSetKeyword*/ +////} +////class J extends B { +//// get identi/*classThatStartedWritingIdentifierOfGetAccessor*/ +////} +////class K extends B { +//// set identi/*classThatStartedWritingIdentifierOfSetAccessor*/ +////} +////class L extends B { +//// public identi/*classThatStartedWritingIdentifierAfterModifier*/ +////} +////class L extends B { +//// static identi/*classThatStartedWritingIdentifierAfterStaticModifier*/ +////} + +const allowedKeywords = [ + "public", + "private", + "protected", + "static", + "abstract", + "readonly", + "get", + "set", + "constructor" +]; + +const allowedKeywordCount = allowedKeywords.length; +function verifyAllowedKeyWords() { + for (const keyword of allowedKeywords) { + verify.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); + } +} + +const nonClassElementMarkers = [ + "InsideMethod" +]; +for (const marker of nonClassElementMarkers) { + goTo.marker(marker); + verify.not.completionListContains("getValue"); + verify.not.completionListIsEmpty(); +} + +// Only keywords allowed at this position since they dont extend the class +const onlyClassElementKeywordLocations = [ + "abstractClass", + "classThatDoesNotExtendAnotherClass" +]; +for (const marker of onlyClassElementKeywordLocations) { + goTo.marker(marker); + verifyAllowedKeyWords(); + verify.completionListCount(allowedKeywordCount); +} + +// Base members and class member keywords allowed +const classElementCompletionLocations = [ + "classThatIsEmptyAndExtendingAnotherClass", + "classThatHasAlreadyImplementedAnotherClassMethod", + "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", + // TODO should we give completion for these keywords + //"classThatHasWrittenPublicKeyword", + //"classElementContainingStatic", + "classThatStartedWritingIdentifier", + "propDeclarationWithoutSemicolon", + "propDeclarationWithSemicolon", + "propAssignmentWithSemicolon", + "propAssignmentWithoutSemicolon", + "methodSignatureWithoutSemicolon", + "methodSignatureWithSemicolon", + "methodImplementation", + "accessorSignatureWithoutSemicolon", + "accessorSignatureImplementation", + // TODO should we give completion for these keywords + //"classThatHasWrittenGetKeyword", + //"classThatHasWrittenSetKeyword", + //"classThatStartedWritingIdentifierOfGetAccessor", + //"classThatStartedWritingIdentifierOfSetAccessor", + //"classThatStartedWritingIdentifierAfterModifier", + //"classThatStartedWritingIdentifierAfterStaticModifier" +]; +for (const marker of classElementCompletionLocations) { + goTo.marker(marker); + verify.completionListContains("getValue", "(method) B.getValue(): number", /*documentation*/ undefined, "method"); + verifyAllowedKeyWords(); + verify.completionListCount(allowedKeywordCount + 1); +} \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInNamedClassExpression.ts b/tests/cases/fourslash/completionListInNamedClassExpression.ts index cf0d170f6a5..8ca6806ce7f 100644 --- a/tests/cases/fourslash/completionListInNamedClassExpression.ts +++ b/tests/cases/fourslash/completionListInNamedClassExpression.ts @@ -1,4 +1,4 @@ -/// +/// //// var x = class myClass { //// getClassName (){ @@ -11,4 +11,4 @@ goTo.marker("0"); verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); goTo.marker("1"); -verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); \ No newline at end of file +verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts b/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts index e1274e6f592..fd347d58037 100644 --- a/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts +++ b/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts @@ -1,4 +1,4 @@ -/// +/// //// class myClass { /*0*/ } //// /*1*/ @@ -16,7 +16,7 @@ //// } goTo.marker("0"); -verify.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); +verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); goTo.marker("1"); @@ -28,7 +28,7 @@ verify.completionListContains("myClass", "(local class) myClass", /*documentatio verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); goTo.marker("3"); -verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); +verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); goTo.marker("4"); @@ -36,5 +36,5 @@ verify.completionListContains("myClass", "class myClass", /*documentation*/ unde verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); goTo.marker("5"); -verify.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); +verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); diff --git a/tests/cases/fourslash/completionListIsGlobalCompletion.ts b/tests/cases/fourslash/completionListIsGlobalCompletion.ts index a1fadc6bb12..121ab940d65 100644 --- a/tests/cases/fourslash/completionListIsGlobalCompletion.ts +++ b/tests/cases/fourslash/completionListIsGlobalCompletion.ts @@ -53,7 +53,7 @@ verify.completionListIsGlobal(false); goTo.marker("9"); verify.completionListIsGlobal(false); goTo.marker("10"); -verify.completionListIsGlobal(true); +verify.completionListIsGlobal(false); goTo.marker("11"); verify.completionListIsGlobal(true); goTo.marker("12"); diff --git a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts index 51e4013e53a..916ad10fe9c 100644 --- a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts +++ b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts @@ -225,27 +225,28 @@ //// ////var shwvar = 1; -function goToMarkAndGeneralVerify(marker: string) +function goToMarkAndGeneralVerify(marker: string, isClassScope?: boolean) { goTo.marker(marker); - verify.completionListContains('mod1var', 'var mod1var: number'); - verify.completionListContains('mod1fn', 'function mod1fn(): void'); - verify.completionListContains('mod1cls', 'class mod1cls'); - verify.completionListContains('mod1int', 'interface mod1int'); - verify.completionListContains('mod1mod', 'namespace mod1mod'); - verify.completionListContains('mod1evar', 'var mod1.mod1evar: number'); - verify.completionListContains('mod1efn', 'function mod1.mod1efn(): void'); - verify.completionListContains('mod1ecls', 'class mod1.mod1ecls'); - verify.completionListContains('mod1eint', 'interface mod1.mod1eint'); - verify.completionListContains('mod1emod', 'namespace mod1.mod1emod'); - verify.completionListContains('mod1eexvar', 'var mod1.mod1eexvar: number'); - verify.completionListContains('mod2', 'namespace mod2'); - verify.completionListContains('mod3', 'namespace mod3'); - verify.completionListContains('shwvar', 'var shwvar: number'); - verify.completionListContains('shwfn', 'function shwfn(): void'); - verify.completionListContains('shwcls', 'class shwcls'); - verify.completionListContains('shwint', 'interface shwint'); + const verifyModule = isClassScope ? verify.not : verify; + verifyModule.completionListContains('mod1var', 'var mod1var: number'); + verifyModule.completionListContains('mod1fn', 'function mod1fn(): void'); + verifyModule.completionListContains('mod1cls', 'class mod1cls'); + verifyModule.completionListContains('mod1int', 'interface mod1int'); + verifyModule.completionListContains('mod1mod', 'namespace mod1mod'); + verifyModule.completionListContains('mod1evar', 'var mod1.mod1evar: number'); + verifyModule.completionListContains('mod1efn', 'function mod1.mod1efn(): void'); + verifyModule.completionListContains('mod1ecls', 'class mod1.mod1ecls'); + verifyModule.completionListContains('mod1eint', 'interface mod1.mod1eint'); + verifyModule.completionListContains('mod1emod', 'namespace mod1.mod1emod'); + verifyModule.completionListContains('mod1eexvar', 'var mod1.mod1eexvar: number'); + verifyModule.completionListContains('mod2', 'namespace mod2'); + verifyModule.completionListContains('mod3', 'namespace mod3'); + verifyModule.completionListContains('shwvar', 'var shwvar: number'); + verifyModule.completionListContains('shwfn', 'function shwfn(): void'); + verifyModule.completionListContains('shwcls', 'class shwcls'); + verifyModule.completionListContains('shwint', 'interface shwint'); verify.not.completionListContains('mod2var'); verify.not.completionListContains('mod2fn'); @@ -280,7 +281,7 @@ verify.completionListContains('bar', '(local var) bar: number'); verify.completionListContains('foob', '(local function) foob(): void'); // from class in mod1 -goToMarkAndGeneralVerify('class'); +goToMarkAndGeneralVerify('class', /*isClassScope*/ true); //verify.not.completionListContains('ceFunc'); //verify.not.completionListContains('ceVar'); @@ -306,7 +307,7 @@ verify.completionListContains('bar', '(local var) bar: number'); verify.completionListContains('foob', '(local function) foob(): void'); // from exported class in mod1 -goToMarkAndGeneralVerify('exportedClass'); +goToMarkAndGeneralVerify('exportedClass', /*isClassScope*/ true); //verify.not.completionListContains('ceFunc'); //verify.not.completionListContains('ceVar'); diff --git a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts index 865887661e9..340d0bd3191 100644 --- a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts +++ b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts @@ -231,6 +231,39 @@ //// x: /*objectLiteral*/ ////} +goTo.marker('extendedClass'); + +verify.not.completionListContains('mod1'); +verify.not.completionListContains('mod2'); +verify.not.completionListContains('mod3'); +verify.not.completionListContains('shwvar', 'var shwvar: number'); +verify.not.completionListContains('shwfn', 'function shwfn(): void'); +verify.not.completionListContains('shwcls', 'class shwcls'); +verify.not.completionListContains('shwint', 'interface shwint'); + +verify.not.completionListContains('mod2var'); +verify.not.completionListContains('mod2fn'); +verify.not.completionListContains('mod2cls'); +verify.not.completionListContains('mod2int'); +verify.not.completionListContains('mod2mod'); +verify.not.completionListContains('mod2evar'); +verify.not.completionListContains('mod2efn'); +verify.not.completionListContains('mod2ecls'); +verify.not.completionListContains('mod2eint'); +verify.not.completionListContains('mod2emod'); +verify.not.completionListContains('sfvar'); +verify.not.completionListContains('sffn'); +verify.not.completionListContains('scvar'); +verify.not.completionListContains('scfn'); +verify.completionListContains('scpfn'); +verify.completionListContains('scpvar'); +verify.not.completionListContains('scsvar'); +verify.not.completionListContains('scsfn'); +verify.not.completionListContains('sivar'); +verify.not.completionListContains('sifn'); +verify.not.completionListContains('mod1exvar'); +verify.not.completionListContains('mod2eexvar'); + function goToMarkerAndVerify(marker: string) { goTo.marker(marker); @@ -267,8 +300,6 @@ function goToMarkerAndVerify(marker: string) verify.not.completionListContains('mod2eexvar'); } -goToMarkerAndVerify('extendedClass'); - goToMarkerAndVerify('objectLiteral'); goTo.marker('localVar'); From 37a2cddabc552e7e3ce86f94d92f171be76f2f97 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 1 May 2017 11:45:18 -0700 Subject: [PATCH 094/282] Give the class element completion on typing keywords like public, private, readonly Also when name of the function is location, make sure we are actually looking at the same symbol before using the declaration to get signature to display --- src/harness/fourslash.ts | 17 +++++ src/services/completions.ts | 41 ++++++++++-- src/services/symbolDisplay.ts | 44 +++++++------ .../completionEntryForClassMembers.ts | 63 +++++++++---------- ...mpletionListBuilderLocations_properties.ts | 2 +- tests/cases/fourslash/fourslash.ts | 2 + ...cesForClassMembersExtendingGenericClass.ts | 2 +- 7 files changed, 111 insertions(+), 60 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a56d21ae345..74790400b98 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -3417,6 +3417,17 @@ namespace FourSlashInterface { export class VerifyNegatable { public not: VerifyNegatable; + public allowedClassElementKeywords = [ + "public", + "private", + "protected", + "static", + "abstract", + "readonly", + "get", + "set", + "constructor" + ]; constructor(protected state: FourSlash.TestState, private negative = false) { if (!negative) { @@ -3453,6 +3464,12 @@ namespace FourSlashInterface { this.state.verifyCompletionListIsEmpty(this.negative); } + public completionListContainsClassElementKeywords() { + for (const keyword of this.allowedClassElementKeywords) { + this.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); + } + } + public completionListIsGlobal(expected: boolean) { this.state.verifyCompletionListIsGlobal(expected); } diff --git a/src/services/completions.ts b/src/services/completions.ts index 44915a958c2..da59dab8828 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -988,6 +988,10 @@ namespace ts.Completions { return undefined; } + function isFromClassElementDeclaration(node: Node) { + return isClassElement(node.parent) && isClassLike(node.parent.parent); + } + /** * Returns the immediate owning class declaration of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -1010,6 +1014,13 @@ namespace ts.Completions { return location; } break; + + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent as ClassLikeDeclaration; + } } } @@ -1148,7 +1159,7 @@ namespace ts.Completions { isFunction(containingNodeKind); case SyntaxKind.StaticKeyword: - return containingNodeKind === SyntaxKind.PropertyDeclaration; + return containingNodeKind === SyntaxKind.PropertyDeclaration && !isClassLike(contextToken.parent.parent); case SyntaxKind.DotDotDotToken: return containingNodeKind === SyntaxKind.Parameter || @@ -1165,13 +1176,17 @@ namespace ts.Completions { containingNodeKind === SyntaxKind.ExportSpecifier || containingNodeKind === SyntaxKind.NamespaceImport; + case SyntaxKind.GetKeyword: + case SyntaxKind.SetKeyword: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case SyntaxKind.ClassKeyword: case SyntaxKind.EnumKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.FunctionKeyword: case SyntaxKind.VarKeyword: - case SyntaxKind.GetKeyword: - case SyntaxKind.SetKeyword: case SyntaxKind.ImportKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.ConstKeyword: @@ -1180,6 +1195,13 @@ namespace ts.Completions { return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } + // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -1373,8 +1395,8 @@ namespace ts.Completions { }); } - const classMemberKeywordCompletions = filter(keywordCompletions, entry => { - switch (stringToToken(entry.name)) { + function isClassMemberCompletionKeyword(kind: SyntaxKind) { + switch (kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: @@ -1386,7 +1408,14 @@ namespace ts.Completions { case SyntaxKind.SetKeyword: return true; } - }); + } + + function isClassMemberCompletionKeywordText(text: string) { + return isClassMemberCompletionKeyword(stringToToken(text)); + } + + const classMemberKeywordCompletions = filter(keywordCompletions, entry => + isClassMemberCompletionKeywordText(entry.name)); function isEqualityExpression(node: Node): node is BinaryExpression { return isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 5bf3e37f28a..4268a52c419 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -200,27 +200,33 @@ namespace ts.SymbolDisplay { (location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it const functionDeclaration = location.parent; - const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); - } - else { - signature = allSignatures[0]; - } + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + const locationIsSymbolDeclaration = findDeclaration(symbol, declaration => + declaration === (location.kind === SyntaxKind.ConstructorKeyword ? functionDeclaration.parent : functionDeclaration)); - if (functionDeclaration.kind === SyntaxKind.Constructor) { - // show (constructor) Type(...) signature - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === SyntaxKind.CallSignature && - !(type.symbol.flags & SymbolFlags.TypeLiteral || type.symbol.flags & SymbolFlags.ObjectLiteral) ? type.symbol : symbol, symbolKind); - } + if (locationIsSymbolDeclaration) { + const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + } + else { + signature = allSignatures[0]; + } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; + if (functionDeclaration.kind === SyntaxKind.Constructor) { + // show (constructor) Type(...) signature + symbolKind = ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === SyntaxKind.CallSignature && + !(type.symbol.flags & SymbolFlags.TypeLiteral || type.symbol.flags & SymbolFlags.ObjectLiteral) ? type.symbol : symbol, symbolKind); + } + + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } } } } diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts index da1051e784a..c52977a0002 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -1,6 +1,9 @@ /// ////abstract class B { +//// private privateMethod() { } +//// protected protectedMethod() { }; +//// static staticMethod() { } //// abstract getValue(): number; //// /*abstractClass*/ ////} @@ -69,25 +72,7 @@ //// static identi/*classThatStartedWritingIdentifierAfterStaticModifier*/ ////} -const allowedKeywords = [ - "public", - "private", - "protected", - "static", - "abstract", - "readonly", - "get", - "set", - "constructor" -]; - -const allowedKeywordCount = allowedKeywords.length; -function verifyAllowedKeyWords() { - for (const keyword of allowedKeywords) { - verify.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); - } -} - +const allowedKeywordCount = verify.allowedClassElementKeywords.length; const nonClassElementMarkers = [ "InsideMethod" ]; @@ -104,7 +89,7 @@ const onlyClassElementKeywordLocations = [ ]; for (const marker of onlyClassElementKeywordLocations) { goTo.marker(marker); - verifyAllowedKeyWords(); + verify.completionListContainsClassElementKeywords(); verify.completionListCount(allowedKeywordCount); } @@ -113,9 +98,8 @@ const classElementCompletionLocations = [ "classThatIsEmptyAndExtendingAnotherClass", "classThatHasAlreadyImplementedAnotherClassMethod", "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", - // TODO should we give completion for these keywords - //"classThatHasWrittenPublicKeyword", - //"classElementContainingStatic", + "classThatHasWrittenPublicKeyword", + "classElementContainingStatic", "classThatStartedWritingIdentifier", "propDeclarationWithoutSemicolon", "propDeclarationWithSemicolon", @@ -126,17 +110,30 @@ const classElementCompletionLocations = [ "methodImplementation", "accessorSignatureWithoutSemicolon", "accessorSignatureImplementation", - // TODO should we give completion for these keywords - //"classThatHasWrittenGetKeyword", - //"classThatHasWrittenSetKeyword", - //"classThatStartedWritingIdentifierOfGetAccessor", - //"classThatStartedWritingIdentifierOfSetAccessor", - //"classThatStartedWritingIdentifierAfterModifier", - //"classThatStartedWritingIdentifierAfterStaticModifier" + "classThatHasWrittenGetKeyword", + "classThatHasWrittenSetKeyword", + "classThatStartedWritingIdentifierOfGetAccessor", + "classThatStartedWritingIdentifierOfSetAccessor", + "classThatStartedWritingIdentifierAfterModifier", + "classThatStartedWritingIdentifierAfterStaticModifier" +]; + +const validMembersOfBase = [ + ["getValue", "(method) B.getValue(): number"], + ["protectedMethod", "(method) B.protectedMethod(): void"] +]; +const invalidMembersOfBase = [ + ["privateMethod", "(method) B.privateMethod(): void"], + ["staticMethod", "(method) B.staticMethod(): void"] ]; for (const marker of classElementCompletionLocations) { goTo.marker(marker); - verify.completionListContains("getValue", "(method) B.getValue(): number", /*documentation*/ undefined, "method"); - verifyAllowedKeyWords(); - verify.completionListCount(allowedKeywordCount + 1); + for (const [validMemberOfBaseSymbol, validMemberOfBaseText] of validMembersOfBase) { + verify.completionListContains(validMemberOfBaseSymbol, validMemberOfBaseText, /*documentation*/ undefined, "method"); + } + for (const [invalidMemberOfBaseSymbol, invalidMemberOfBaseText] of invalidMembersOfBase) { + verify.not.completionListContains(invalidMemberOfBaseSymbol, invalidMemberOfBaseText, /*documentation*/ undefined, "method"); + } + verify.completionListContainsClassElementKeywords(); + verify.completionListCount(allowedKeywordCount + validMembersOfBase.length); } \ No newline at end of file diff --git a/tests/cases/fourslash/completionListBuilderLocations_properties.ts b/tests/cases/fourslash/completionListBuilderLocations_properties.ts index 806d8c1de4f..2cdc3b7e7ba 100644 --- a/tests/cases/fourslash/completionListBuilderLocations_properties.ts +++ b/tests/cases/fourslash/completionListBuilderLocations_properties.ts @@ -10,4 +10,4 @@ //// public static a/*property2*/ ////} -goTo.eachMarker(() => verify.completionListIsEmpty()); +goTo.eachMarker(() => verify.completionListContainsClassElementKeywords()); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 374dfd33c7d..31d8b8b4ef2 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -133,11 +133,13 @@ declare namespace FourSlashInterface { class verifyNegatable { private negative; not: verifyNegatable; + allowedClassElementKeywords: string[]; constructor(negative?: boolean); completionListCount(expectedCount: number): void; completionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number): void; completionListItemsCountIsGreaterThan(count: number): void; completionListIsEmpty(): void; + completionListContainsClassElementKeywords(): void; completionListAllowsNewIdentifier(): void; signatureHelpPresent(): void; errorExistsBetweenMarkers(startMarker: string, endMarker: string): void; diff --git a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts index 3e453663f63..448c2627531 100644 --- a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts +++ b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts @@ -26,7 +26,7 @@ const methods = ranges.get("method"); const [m0, m1, m2] = methods; verify.referenceGroups(m0, [{ definition: "(method) Base.method(a?: T, b?: U): this", ranges: methods }]); verify.referenceGroups(m1, [ - { definition: "(method) Base.method(): void", ranges: [m0] }, + { definition: "(method) Base.method(a?: T, b?: U): this", ranges: [m0] }, { definition: "(method) MyClass.method(): void", ranges: [m1, m2] } ]); verify.referenceGroups(m2, [ From fcb0f4617812dae7fdf2c7dd97a508e2535e3c3f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 4 May 2017 17:44:34 -0700 Subject: [PATCH 095/282] Tune the completion list for static and private modifiers Do not show inherited members in completion for when writing private member Show only static inherited members when writing static member --- src/services/completions.ts | 39 +++++-- .../completionEntryForClassMembers.ts | 107 ++++++++++++------ 2 files changed, 107 insertions(+), 39 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index da59dab8828..cb4abb89b58 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -939,10 +939,31 @@ namespace ts.Completions { const baseTypeNode = getClassExtendsHeritageClauseElement(classLikeDeclaration); if (baseTypeNode) { - const baseType = typeChecker.getTypeAtLocation(baseTypeNode); - // List of property symbols of base type that are not private - symbols = filter(typeChecker.getPropertiesOfType(baseType), - baseProperty => !(getDeclarationModifierFlagsFromSymbol(baseProperty) & ModifierFlags.Private)); + const classElement = contextToken.parent; + let classElementModifierFlags = isClassElement(classElement) && getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === SyntaxKind.Identifier && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | ModifierFlags.Private; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | ModifierFlags.Static; + break; + } + } + + // No member list for private methods + if (!(classElementModifierFlags & ModifierFlags.Private)) { + const baseType = typeChecker.getTypeAtLocation(baseTypeNode); + const typeToGetPropertiesFrom = (classElementModifierFlags & ModifierFlags.Static) ? + typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, classLikeDeclaration) : + baseType; + + // List of property symbols of base type that are not private + symbols = filter(typeChecker.getPropertiesOfType(typeToGetPropertiesFrom), + baseProperty => baseProperty.getDeclarations() && !(getDeclarationModifierFlagsFromSymbol(baseProperty) & ModifierFlags.Private)); + } } return true; @@ -1248,7 +1269,7 @@ namespace ts.Completions { for (const element of namedImportsOrExports) { // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } @@ -1287,7 +1308,7 @@ namespace ts.Completions { } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } @@ -1322,7 +1343,7 @@ namespace ts.Completions { const seenNames = createMap(); for (const attr of attributes) { // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } @@ -1333,6 +1354,10 @@ namespace ts.Completions { return filter(symbols, a => !seenNames.get(a.name)); } + + function isCurrentlyEditingNode(node: Node): boolean { + return node.getStart() <= position && position <= node.getEnd(); + } } /** diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts index c52977a0002..672046f62a7 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -23,12 +23,19 @@ ////class F extends B { //// public /*classThatHasWrittenPublicKeyword*/ ////} +////class F2 extends B { +//// private /*classThatHasWrittenPrivateKeyword*/ +////} ////class G extends B { //// static /*classElementContainingStatic*/ ////} +////class G2 extends B { +//// private static /*classElementContainingPrivateStatic*/ +////} ////class H extends B { //// prop/*classThatStartedWritingIdentifier*/ ////} +//////Class for location verification ////class I extends B { //// prop0: number //// /*propDeclarationWithoutSemicolon*/ @@ -68,38 +75,87 @@ ////class L extends B { //// public identi/*classThatStartedWritingIdentifierAfterModifier*/ ////} -////class L extends B { +////class L2 extends B { +//// private identi/*classThatStartedWritingIdentifierAfterPrivateModifier*/ +////} +////class M extends B { //// static identi/*classThatStartedWritingIdentifierAfterStaticModifier*/ ////} +////class M extends B { +//// private static identi/*classThatStartedWritingIdentifierAfterPrivateStaticModifier*/ +////} const allowedKeywordCount = verify.allowedClassElementKeywords.length; +type CompletionInfo = [string, string]; +type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] }; + +function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) { + for (const marker of classElementCompletionLocations) { + goTo.marker(marker); + verifyCompletionInfo(validMembers, verify); + verifyCompletionInfo(invalidMembers, verify.not); + verify.completionListContainsClassElementKeywords(); + verify.completionListCount(allowedKeywordCount + validMembers.length); + } +} + +function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) { + for (const [symbol, text] of memberInfo) { + verify.completionListContains(symbol, text, /*documentation*/ undefined, "method"); + } +} + +const allMembersOfBase: CompletionInfo[] = [ + ["getValue", "(method) B.getValue(): number"], + ["protectedMethod", "(method) B.protectedMethod(): void"], + ["privateMethod", "(method) B.privateMethod(): void"], + ["staticMethod", "(method) B.staticMethod(): void"] +]; +function filterCompletionInfo(fn: (a: CompletionInfo) => boolean): CompletionInfoVerifier { + const validMembers: CompletionInfo[] = []; + const invalidMembers: CompletionInfo[] = []; + for (const member of allMembersOfBase) { + if (fn(member)) { + validMembers.push(member); + } + else { + invalidMembers.push(member); + } + } + return { validMembers, invalidMembers }; +} + + +const instanceMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue" || a === "protectedMethod"); +const staticMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "staticMethod"); + +// Not a class element declaration location const nonClassElementMarkers = [ "InsideMethod" ]; for (const marker of nonClassElementMarkers) { goTo.marker(marker); - verify.not.completionListContains("getValue"); + verifyCompletionInfo(allMembersOfBase, verify.not); verify.not.completionListIsEmpty(); } -// Only keywords allowed at this position since they dont extend the class +// Only keywords allowed at this position since they dont extend the class or are private const onlyClassElementKeywordLocations = [ "abstractClass", - "classThatDoesNotExtendAnotherClass" + "classThatDoesNotExtendAnotherClass", + "classThatHasWrittenPrivateKeyword", + "classElementContainingPrivateStatic", + "classThatStartedWritingIdentifierAfterPrivateModifier", + "classThatStartedWritingIdentifierAfterPrivateStaticModifier" ]; -for (const marker of onlyClassElementKeywordLocations) { - goTo.marker(marker); - verify.completionListContainsClassElementKeywords(); - verify.completionListCount(allowedKeywordCount); -} +verifyClassElementLocations({ validMembers: [], invalidMembers: allMembersOfBase }, onlyClassElementKeywordLocations); -// Base members and class member keywords allowed -const classElementCompletionLocations = [ +// Instance base members and class member keywords allowed +const classInstanceElementLocations = [ "classThatIsEmptyAndExtendingAnotherClass", "classThatHasAlreadyImplementedAnotherClassMethod", "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", "classThatHasWrittenPublicKeyword", - "classElementContainingStatic", "classThatStartedWritingIdentifier", "propDeclarationWithoutSemicolon", "propDeclarationWithSemicolon", @@ -115,25 +171,12 @@ const classElementCompletionLocations = [ "classThatStartedWritingIdentifierOfGetAccessor", "classThatStartedWritingIdentifierOfSetAccessor", "classThatStartedWritingIdentifierAfterModifier", +]; +verifyClassElementLocations(instanceMemberInfo, classInstanceElementLocations); + +// Static Base members and class member keywords allowed +const staticClassLocations = [ + "classElementContainingStatic", "classThatStartedWritingIdentifierAfterStaticModifier" ]; - -const validMembersOfBase = [ - ["getValue", "(method) B.getValue(): number"], - ["protectedMethod", "(method) B.protectedMethod(): void"] -]; -const invalidMembersOfBase = [ - ["privateMethod", "(method) B.privateMethod(): void"], - ["staticMethod", "(method) B.staticMethod(): void"] -]; -for (const marker of classElementCompletionLocations) { - goTo.marker(marker); - for (const [validMemberOfBaseSymbol, validMemberOfBaseText] of validMembersOfBase) { - verify.completionListContains(validMemberOfBaseSymbol, validMemberOfBaseText, /*documentation*/ undefined, "method"); - } - for (const [invalidMemberOfBaseSymbol, invalidMemberOfBaseText] of invalidMembersOfBase) { - verify.not.completionListContains(invalidMemberOfBaseSymbol, invalidMemberOfBaseText, /*documentation*/ undefined, "method"); - } - verify.completionListContainsClassElementKeywords(); - verify.completionListCount(allowedKeywordCount + validMembersOfBase.length); -} \ No newline at end of file +verifyClassElementLocations(staticMemberInfo, staticClassLocations); \ No newline at end of file From d2bda47e80f94b60cc8971a55c39e86f1f6455ab Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 12:39:47 -0700 Subject: [PATCH 096/282] fix inTypeAlias logic --- src/compiler/checker.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6ee3377d88a..5e7ce03afe1 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2297,7 +2297,6 @@ namespace ts { InFirstTypeArgument: boolean; // Writing first type argument of the instantiated type // TODO: ??? InTypeAlias: boolean; // Writing type in type alias declaration - checkAlias: boolean; symbolStack: Symbol[] | undefined; } @@ -2310,7 +2309,6 @@ namespace ts { InElementType: false, InFirstTypeArgument: false, InTypeAlias: false, - checkAlias: true, symbolStack: undefined }; } @@ -2319,6 +2317,8 @@ namespace ts { const InElementType = context.InElementType; // TODO: why doesn't tts unset the flag? context.InElementType = false; + const inTypeAlias = context.InTypeAlias; + context.InTypeAlias = false; // TODO: should be assert? if (!type) { @@ -2406,12 +2406,11 @@ namespace ts { return createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!context.InTypeAlias && context.checkAlias && type.aliasSymbol) { + if (!inTypeAlias && type.aliasSymbol) { const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, context); const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, /*addInElementTypeFlag*/ false); return createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; From 573040f0cfa713929bfa1fe84f4fd2a81cc82658 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Fri, 5 May 2017 13:47:28 -0700 Subject: [PATCH 097/282] Convert `Declaration` to union, not type hierarchy --- src/compiler/binder.ts | 6 +- src/compiler/checker.ts | 20 +-- src/compiler/transformers/es2015.ts | 2 +- src/compiler/types.ts | 182 ++++++++++++++++++++++------ src/compiler/utilities.ts | 67 +++++----- 5 files changed, 190 insertions(+), 87 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 38cb93bff7e..8506378e216 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -304,7 +304,7 @@ namespace ts { } function getDisplayName(node: Declaration): string { - return (node as RealDeclaration).name ? declarationNameToString((node as RealDeclaration).name) : getDeclarationName(node); + return (node as DeclarationBase).name ? declarationNameToString((node as DeclarationBase).name) : getDeclarationName(node); } /** @@ -367,8 +367,8 @@ namespace ts { symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } else { - if ((node as RealDeclaration).name) { - (node as RealDeclaration).name.parent = node; + if ((node as DeclarationBase).name) { + (node as DeclarationBase).name.parent = node; } // Report errors every position with duplicate declaration diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8979510461e..05af363fb8e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3621,7 +3621,7 @@ namespace ts { }); } - function isDeclarationVisible(node: Declaration): boolean { + function isDeclarationVisible(node: Node): boolean { if (node) { const links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -3635,10 +3635,10 @@ namespace ts { function determineIfDeclarationIsVisible() { switch (node.kind) { case SyntaxKind.BindingElement: - return isDeclarationVisible(node.parent.parent); + return isDeclarationVisible(node.parent.parent); case SyntaxKind.VariableDeclaration: - if (isBindingPattern(node.name) && - !(node.name).elements.length) { + const declaration = node as VariableDeclaration; + if (isBindingPattern(declaration.name) && !declaration.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } @@ -3661,7 +3661,7 @@ namespace ts { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent); + return isDeclarationVisible(parent); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: @@ -3691,7 +3691,7 @@ namespace ts { case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: case SyntaxKind.ParenthesizedType: - return isDeclarationVisible(node.parent); + return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible @@ -6236,8 +6236,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return (node).name.kind === SyntaxKind.ComputedPropertyName - && traverse((node).name); + return (node).name.kind === SyntaxKind.ComputedPropertyName + && traverse((node).name); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && forEachChild(node, traverse); @@ -21917,7 +21917,7 @@ namespace ts { function isTypeDeclarationName(name: Node): boolean { return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && - (name.parent).name === name; + (name.parent).name === name; } function isTypeDeclaration(node: Node): boolean { @@ -22545,7 +22545,7 @@ namespace ts { // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node: Declaration): boolean { + function isDeclarationWithCollidingName(node: Node): boolean { node = getParseTreeNode(node, isDeclaration); if (node) { const symbol = getSymbolOfNode(node); diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 188da04b36c..4165b0679e1 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -3748,7 +3748,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.VariableDeclaration: - return (parent).name === node + return (parent).name === node && resolver.isDeclarationWithCollidingName(parent); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 51e9d6717ee..de71fbfdabe 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -603,15 +603,75 @@ namespace ts { export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; - export interface RealDeclaration extends Node { + export interface DeclarationBase extends Node { _declarationBrand: any; name?: DeclarationName; } - // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files - export type Declaration = RealDeclaration | BinaryExpression; + export type Declaration = + | ArrowFunction + // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files + | BinaryExpression + | BindingElement + | CallExpression + | CallSignatureDeclaration + | ClassDeclaration + | ClassElement + | ClassExpression + | ClassLikeDeclaration + | ConstructSignatureDeclaration + | ConstructorDeclaration + | ConstructorTypeNode + | EnumDeclaration + | EnumMember + | ExportAssignment + | ExportDeclaration + | ExportSpecifier + | FunctionDeclaration + | FunctionExpression + | FunctionTypeNode + | GetAccessorDeclaration + | ImportClause + | ImportEqualsDeclaration + | ImportSpecifier + | IndexSignatureDeclaration + | InterfaceDeclaration + | JSDocFunctionType + | JSDocNamespaceDeclaration + | JSDocPropertyTag + | JSDocTypedefTag + | JsxAttribute + | JsxAttributes + | JsxSpreadAttribute + | MappedTypeNode + | MethodDeclaration + | MethodSignature + | MissingDeclaration + | ModuleDeclaration + | NamespaceDeclaration + | NamespaceExportDeclaration + | NamespaceImport + | NewExpression + | ObjectLiteralExpression + | ParameterDeclaration + | PropertyAccessExpression + | PropertyAssignment + | PropertyDeclaration + | PropertySignature + | SemicolonClassElement + | SetAccessorDeclaration + | ShorthandPropertyAssignment + | SignatureDeclaration + | SourceFile + | SpreadAssignment + | TypeAliasDeclaration + | TypeElement + | TypeLiteralNode + | TypeParameterDeclaration + | VariableDeclaration + | VariableLikeDeclaration; - export interface DeclarationStatement extends RealDeclaration, Statement { + export interface DeclarationStatement extends DeclarationBase, Statement { name?: Identifier | StringLiteral | NumericLiteral; } @@ -625,7 +685,7 @@ namespace ts { expression: LeftHandSideExpression; } - export interface TypeParameterDeclaration extends RealDeclaration { + export interface TypeParameterDeclaration extends DeclarationBase { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -636,7 +696,23 @@ namespace ts { expression?: Expression; } - export interface SignatureDeclaration extends RealDeclaration { + export interface SignatureDeclaration extends DeclarationBase { + kind: + | SyntaxKind.CallSignature + | SyntaxKind.ConstructSignature + | SyntaxKind.ConstructorType + | SyntaxKind.MethodSignature + | SyntaxKind.IndexSignature + | SyntaxKind.FunctionType + | SyntaxKind.JSDocFunctionType + | SyntaxKind.FunctionDeclaration + | SyntaxKind.MethodDeclaration + | SyntaxKind.GetAccessor + | SyntaxKind.SetAccessor + | SyntaxKind.Constructor + | SyntaxKind.ArrowFunction + | SyntaxKind.FunctionExpression + name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -653,7 +729,7 @@ namespace ts { export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends RealDeclaration { + export interface VariableDeclaration extends DeclarationBase { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; // Declared variable name @@ -667,7 +743,7 @@ namespace ts { declarations: NodeArray; } - export interface ParameterDeclaration extends RealDeclaration { + export interface ParameterDeclaration extends DeclarationBase { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; // Present on rest parameter @@ -677,7 +753,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface BindingElement extends RealDeclaration { + export interface BindingElement extends DeclarationBase { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; // Binding property name (in object binding pattern) @@ -702,7 +778,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface ObjectLiteralElement extends RealDeclaration { + export interface ObjectLiteralElement extends DeclarationBase { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -737,16 +813,24 @@ namespace ts { expression: Expression; } - // SyntaxKind.VariableDeclaration - // SyntaxKind.Parameter - // SyntaxKind.BindingElement - // SyntaxKind.Property - // SyntaxKind.PropertyAssignment - // SyntaxKind.JsxAttribute - // SyntaxKind.ShorthandPropertyAssignment - // SyntaxKind.EnumMember - // SyntaxKind.JSDocPropertyTag - export interface VariableLikeDeclaration extends RealDeclaration { + /** + * There aren't any explicit subtypes of VariableLikeDeclaration; + * it's just structurally relatable to a number of types. + * (Maybe it should be an intersection of the below types.) + */ + export interface VariableLikeDeclaration extends DeclarationBase { + kind: + | SyntaxKind.VariableDeclaration + | SyntaxKind.Parameter + | SyntaxKind.BindingElement + | SyntaxKind.PropertyAssignment + | SyntaxKind.PropertyDeclaration + | SyntaxKind.PropertySignature + | SyntaxKind.JsxAttribute + | SyntaxKind.ShorthandPropertyAssignment + | SyntaxKind.EnumMember + | SyntaxKind.JSDocPropertyTag + | SyntaxKind.JSDocRecordMember; propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -755,10 +839,6 @@ namespace ts { initializer?: Expression; } - export interface PropertyLikeDeclaration extends RealDeclaration { - name: PropertyName; - } - export interface ObjectBindingPattern extends Node { kind: SyntaxKind.ObjectBindingPattern; parent?: VariableDeclaration | ParameterDeclaration | BindingElement; @@ -904,7 +984,7 @@ namespace ts { } // A TypeLiteral is the declaration node for an anonymous symbol. - export interface TypeLiteralNode extends TypeNode, RealDeclaration { + export interface TypeLiteralNode extends TypeNode, DeclarationBase { kind: SyntaxKind.TypeLiteral; members: NodeArray; } @@ -948,7 +1028,7 @@ namespace ts { indexType: TypeNode; } - export interface MappedTypeNode extends TypeNode, RealDeclaration { + export interface MappedTypeNode extends TypeNode, DeclarationBase { kind: SyntaxKind.MappedType; parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; @@ -1405,7 +1485,7 @@ namespace ts { * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) */ - export interface ObjectLiteralExpressionBase extends PrimaryExpression, RealDeclaration { + export interface ObjectLiteralExpressionBase extends PrimaryExpression, DeclarationBase { properties: NodeArray; } @@ -1419,7 +1499,7 @@ namespace ts { export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - export interface PropertyAccessExpression extends MemberExpression, RealDeclaration { + export interface PropertyAccessExpression extends MemberExpression, DeclarationBase { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1451,7 +1531,7 @@ namespace ts { | SuperElementAccessExpression ; - export interface CallExpression extends LeftHandSideExpression, RealDeclaration { + export interface CallExpression extends LeftHandSideExpression, DeclarationBase { kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1470,7 +1550,7 @@ namespace ts { typeArguments?: NodeArray; } - export interface NewExpression extends PrimaryExpression, RealDeclaration { + export interface NewExpression extends PrimaryExpression, DeclarationBase { kind: SyntaxKind.NewExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1528,6 +1608,7 @@ namespace ts { export type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; export interface JsxAttributes extends ObjectLiteralExpressionBase { + kind: SyntaxKind.JsxAttributes; parent?: JsxOpeningLikeElement; } @@ -1764,7 +1845,10 @@ namespace ts { export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - export interface ClassLikeDeclaration extends RealDeclaration { + export interface ClassLikeDeclaration extends DeclarationBase { + kind: + | SyntaxKind.ClassDeclaration + | SyntaxKind.ClassExpression; name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1780,12 +1864,30 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export interface ClassElement extends RealDeclaration { + export interface ClassElement extends DeclarationBase { + kind: + | SyntaxKind.PropertyDeclaration + | SyntaxKind.MethodDeclaration + | SyntaxKind.Constructor + | SyntaxKind.SemicolonClassElement + | SyntaxKind.GetAccessor + | SyntaxKind.SetAccessor + | SyntaxKind.IndexSignature + | SyntaxKind.MissingDeclaration; _classElementBrand: any; name?: PropertyName; } - export interface TypeElement extends RealDeclaration { + export interface TypeElement extends DeclarationBase { + kind: + | SyntaxKind.CallSignature + | SyntaxKind.ConstructSignature + | SyntaxKind.PropertySignature + | SyntaxKind.MethodSignature + | SyntaxKind.IndexSignature + | SyntaxKind.MissingDeclaration + | SyntaxKind.JSDocPropertyTag + | SyntaxKind.JSDocRecordMember; _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1813,7 +1915,7 @@ namespace ts { type: TypeNode; } - export interface EnumMember extends RealDeclaration { + export interface EnumMember extends DeclarationBase { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; // This does include ComputedPropertyName, but the parser will give an error @@ -1902,14 +2004,14 @@ namespace ts { // import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns } // import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} // import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} - export interface ImportClause extends RealDeclaration { + export interface ImportClause extends DeclarationBase { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; // Default binding namedBindings?: NamedImportBindings; } - export interface NamespaceImport extends RealDeclaration { + export interface NamespaceImport extends DeclarationBase { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1942,14 +2044,14 @@ namespace ts { export type NamedImportsOrExports = NamedImports | NamedExports; - export interface ImportSpecifier extends RealDeclaration { + export interface ImportSpecifier extends DeclarationBase { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) name: Identifier; // Declared name } - export interface ExportSpecifier extends RealDeclaration { + export interface ExportSpecifier extends DeclarationBase { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) @@ -2115,7 +2217,7 @@ namespace ts { typeExpression: JSDocTypeExpression; } - export interface JSDocTypedefTag extends JSDocTag, RealDeclaration { + export interface JSDocTypedefTag extends JSDocTag, DeclarationBase { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2249,7 +2351,7 @@ namespace ts { // Source files are declarations when they are external modules. - export interface SourceFile extends RealDeclaration { + export interface SourceFile extends DeclarationBase { kind: SyntaxKind.SourceFile; statements: NodeArray; endOfFileToken: Token; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5b1cbb849bc..e38f0ad331a 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -11,36 +11,6 @@ namespace ts { isTypeReferenceDirective?: boolean; } - export function getNameOfDeclaration(declaration: Declaration): DeclarationName { - if (!declaration) { - return undefined; - } - if (declaration.kind === SyntaxKind.BinaryExpression) { - const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression); - const lhs = (declaration as BinaryExpression).left; - switch (kind) { - case SpecialPropertyAssignmentKind.None: - case SpecialPropertyAssignmentKind.ModuleExports: - return undefined; - case SpecialPropertyAssignmentKind.ExportsProperty: - if (lhs.kind === SyntaxKind.Identifier) { - return (lhs as PropertyAccessExpression).name; - } - else { - return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; - } - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - return (lhs as PropertyAccessExpression).name; - case SpecialPropertyAssignmentKind.PrototypeProperty: - return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; - } - } - else { - return declaration.name; - } - } - export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { const declarations = symbol.declarations; if (declarations) { @@ -596,7 +566,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.TypeAliasDeclaration: - errorNode = (node).name; + errorNode = (node).name; break; case SyntaxKind.ArrowFunction: return getErrorSpanForArrowFunction(sourceFile, node); @@ -1806,6 +1776,37 @@ namespace ts { return false; } + export function getNameOfDeclaration(declaration: Declaration): DeclarationName { + if (!declaration) { + return undefined; + } + if (declaration.kind === SyntaxKind.BinaryExpression) { + const kind = getSpecialPropertyAssignmentKind(declaration); + const lhs = (declaration as BinaryExpression).left; + switch (kind) { + case SpecialPropertyAssignmentKind.None: + case SpecialPropertyAssignmentKind.ModuleExports: + return undefined; + case SpecialPropertyAssignmentKind.ExportsProperty: + if (lhs.kind === SyntaxKind.Identifier) { + return (lhs as PropertyAccessExpression).name; + } + else { + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + case SpecialPropertyAssignmentKind.ThisProperty: + case SpecialPropertyAssignmentKind.Property: + return (lhs as PropertyAccessExpression).name; + case SpecialPropertyAssignmentKind.PrototypeProperty: + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + } + else { + return declaration.name; + } + } + + export function isLiteralComputedPropertyDeclarationName(node: Node) { return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) && node.parent.kind === SyntaxKind.ComputedPropertyName && @@ -1826,7 +1827,7 @@ namespace ts { case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyAccessExpression: // Name in member declaration or property name in property access - return (parent).name === node; + return (parent).name === node; case SyntaxKind.QualifiedName: // Name on right hand side of dot in a type query if ((parent).right === node) { @@ -4101,7 +4102,7 @@ namespace ts { || kind === SyntaxKind.MergeDeclarationMarker; } - export function isDeclaration(node: Node): node is RealDeclaration { + export function isDeclaration(node: Node): node is DeclarationBase { return isDeclarationKind(node.kind); } From a5bef216aea8b871f7f23a78b260a4d635cffb74 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 13:47:51 -0700 Subject: [PATCH 098/282] Use `symbolToName` instead of copying --- src/compiler/checker.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5e7ce03afe1..18a6c03c6d6 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2287,7 +2287,7 @@ namespace ts { interface NodeBuilderContext { readonly enclosingDeclaration: Node | undefined; readonly flags: NodeBuilderFlags | undefined; - + // State encounteredError: boolean; inObjectTypeLiteral: boolean; @@ -2564,7 +2564,6 @@ namespace ts { return createTypeLiteralNode(members); } - function shouldAddParenthesisAroundFunctionType(callSignature: Signature, context: NodeBuilderContext) { if (InElementType) { return true; @@ -2670,13 +2669,10 @@ namespace ts { return typeElements; } + // TODO: make logic mirror that of writeObjectLiteralType for (const propertySymbol of properties) { const propertyType = getTypeOfSymbol(propertySymbol); - const oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0] as TypeElement; - if (!oldDeclaration) { - return; - } - const propertyName = getDeepSynthesizedClone(oldDeclaration.name); + const propertyName = symbolToName(propertySymbol, /*expectsIdentifier*/ true, context); const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? createToken(SyntaxKind.QuestionToken) : undefined; if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length) { const signatures = getSignaturesOfType(propertyType, SignatureKind.Call); @@ -2697,7 +2693,7 @@ namespace ts { propertyName, optionalToken, propertyTypeNode, - /*initializer*/undefined); + /*initializer*/ undefined); typeElements.push(propertySignature); } } @@ -2744,8 +2740,8 @@ namespace ts { const returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if(context.flags & NodeBuilderFlags.SuppressAnyReturnType) { - if(returnTypeNode && returnTypeNode.kind === SyntaxKind.AnyKeyword) { + if (context.flags & NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === SyntaxKind.AnyKeyword) { returnTypeNode = undefined; } } From b39c319f0c4ee9b460ed51eba77e8c0958896c80 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Fri, 5 May 2017 13:48:45 -0700 Subject: [PATCH 099/282] Fix lint --- src/compiler/types.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index de71fbfdabe..043c8b9a0b1 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -711,7 +711,7 @@ namespace ts { | SyntaxKind.SetAccessor | SyntaxKind.Constructor | SyntaxKind.ArrowFunction - | SyntaxKind.FunctionExpression + | SyntaxKind.FunctionExpression; name?: PropertyName; typeParameters?: NodeArray; @@ -814,9 +814,8 @@ namespace ts { } /** - * There aren't any explicit subtypes of VariableLikeDeclaration; + * There aren't any explicit subtypes of VariableLikeDeclaration, * it's just structurally relatable to a number of types. - * (Maybe it should be an intersection of the below types.) */ export interface VariableLikeDeclaration extends DeclarationBase { kind: From b8bb0c22f3261a28d05e3d3aaae15d652d9d6087 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 14:47:57 -0700 Subject: [PATCH 100/282] emit type parameter's default --- src/compiler/emitter.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index eebbe302898..cd16074d572 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -814,6 +814,7 @@ namespace ts { function emitTypeParameter(node: TypeParameterDeclaration) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node: ParameterDeclaration) { From a1d2049c29af925f3bc6d8ff09dee299d250edb2 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 14:48:20 -0700 Subject: [PATCH 101/282] convert type format flags --- src/compiler/checker.ts | 49 +++++++++++++++++++++++++++++++++++++++-- src/compiler/types.ts | 2 +- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 18a6c03c6d6..6496b191eac 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2242,10 +2242,49 @@ namespace ts { return result; } + function typeFormatFlagsToNodeBuilderFlags(flags: TypeFormatFlags): NodeBuilderFlags { + let result = NodeBuilderFlags.None; + if (flags & TypeFormatFlags.WriteArrayAsGenericType) { + result |= NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & TypeFormatFlags.UseTypeOfFunction) { + result |= NodeBuilderFlags.UseTypeOfFunction; + } + if (flags & TypeFormatFlags.NoTruncation) { + result |= NodeBuilderFlags.NoTruncation; + } + if (flags & TypeFormatFlags.WriteArrowStyleSignature) { + result |= NodeBuilderFlags.WriteArrowStyleSignature; + } + if (flags & TypeFormatFlags.WriteOwnNameForAnyLike) { + result |= NodeBuilderFlags.WriteOwnNameForAnyLike; + } + if (flags & TypeFormatFlags.WriteArrayAsGenericType) { + result |= NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & TypeFormatFlags.WriteTypeArgumentsOfSignature) { + result |= NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + if (flags & TypeFormatFlags.UseFullyQualifiedType) { + result |= NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & TypeFormatFlags.UseTypeAliasValue) { + result |= NodeBuilderFlags.UseTypeAliasValue; + } + if (flags & TypeFormatFlags.SuppressAnyReturnType) { + result |= NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & TypeFormatFlags.AddUndefined) { + result |= NodeBuilderFlags.AddUndefined; + } + + return result; + } + function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { const str = oldTypeToString(type, enclosingDeclaration, flags); str; const str2 = oldTypeToString(type, enclosingDeclaration, flags); str2; - const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, NodeBuilderFlags.ignoreErrors); + const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, typeFormatFlagsToNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors, !!(flags & TypeFormatFlags.InTypeAlias)); Debug.assert(typeNode !== undefined, "should always get typenode?"); const newLine = NewLineKind.None; const options = { newLine, removeComments: true }; @@ -2264,8 +2303,9 @@ namespace ts { function createNodeBuilder() { return { - typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { + typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, inTypeAlias?: boolean) => { const context = createNodeBuilderContext(enclosingDeclaration, flags); + context.InTypeAlias = inTypeAlias; const resultingNode = typeToTypeNodeHelper(type, context); const result = context.encounteredError ? undefined : resultingNode; return result; @@ -2403,6 +2443,7 @@ namespace ts { if (type.flags & TypeFlags.TypeParameter) { const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. + // TODO: add constraint here? return createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -2585,6 +2626,10 @@ namespace ts { function typeReferenceToTypeNode(type: TypeReference) { const typeArguments: Type[] = type.typeArguments || emptyArray; if (type.target === globalArrayType) { + if (context.flags & NodeBuilderFlags.WriteArrayAsGenericType) { + const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return createTypeReferenceNode("Array", [typeArgumentNode]); + } context.InElementType = true; const elementType = typeToTypeNodeHelper(typeArguments[0], context); context.InElementType = false; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 17df0243a1b..48c4b2cd4ac 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2496,7 +2496,7 @@ namespace ts { /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, inTypeAlias?: boolean): TypeNode; /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ From 818bfdcd88c798e2b6141e9f1cfd8082d7b9d710 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 15:08:02 -0700 Subject: [PATCH 102/282] accessibility check --- src/compiler/checker.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6496b191eac..5302f43bcc7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2443,11 +2443,11 @@ namespace ts { if (type.flags & TypeFlags.TypeParameter) { const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - // TODO: add constraint here? return createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!inTypeAlias && type.aliasSymbol) { + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, context); const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, /*addInElementTypeFlag*/ false); return createTypeReferenceNode(name, typeArgumentNodes); From 6a175321bf432f31490dd81fcc7fd0f7257c4baa Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Fri, 5 May 2017 15:09:54 -0700 Subject: [PATCH 103/282] Address comments: simplify, dedupe and clean up --- src/compiler/checker.ts | 24 ++++++++---------------- src/compiler/utilities.ts | 29 +++++++++++++++-------------- 2 files changed, 23 insertions(+), 30 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 05af363fb8e..aea175ac8b1 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -18110,18 +18110,17 @@ namespace ts { forEach(overloads, o => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - const name = getNameOfDeclaration(o); if (deviation & ModifierFlags.Export) { - error(name, Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & ModifierFlags.Ambient) { - error(name, Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (ModifierFlags.Private | ModifierFlags.Protected)) { - error(name || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & ModifierFlags.Abstract) { - error(name, Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -20317,19 +20316,12 @@ namespace ts { return; } - let errorNode: Node; - if (propDeclaration && propDeclaration.kind === SyntaxKind.BinaryExpression) { - const specialAssignmentKind = getSpecialPropertyAssignmentKind(propDeclaration as BinaryExpression); - if (specialAssignmentKind === SpecialPropertyAssignmentKind.Property || - specialAssignmentKind === SpecialPropertyAssignmentKind.PrototypeProperty || - specialAssignmentKind === SpecialPropertyAssignmentKind.ThisProperty) { - errorNode = propDeclaration; - } - } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class + let errorNode: Node; if (propDeclaration && - (getNameOfDeclaration(propDeclaration).kind === SyntaxKind.ComputedPropertyName || + (propDeclaration.kind === SyntaxKind.BinaryExpression || + getNameOfDeclaration(propDeclaration).kind === SyntaxKind.ComputedPropertyName || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index e38f0ad331a..7b92dbf68b5 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1784,21 +1784,21 @@ namespace ts { const kind = getSpecialPropertyAssignmentKind(declaration); const lhs = (declaration as BinaryExpression).left; switch (kind) { - case SpecialPropertyAssignmentKind.None: - case SpecialPropertyAssignmentKind.ModuleExports: - return undefined; - case SpecialPropertyAssignmentKind.ExportsProperty: - if (lhs.kind === SyntaxKind.Identifier) { + case SpecialPropertyAssignmentKind.None: + case SpecialPropertyAssignmentKind.ModuleExports: + return undefined; + case SpecialPropertyAssignmentKind.ExportsProperty: + if (lhs.kind === SyntaxKind.Identifier) { + return (lhs as PropertyAccessExpression).name; + } + else { + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + case SpecialPropertyAssignmentKind.ThisProperty: + case SpecialPropertyAssignmentKind.Property: return (lhs as PropertyAccessExpression).name; - } - else { + case SpecialPropertyAssignmentKind.PrototypeProperty: return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; - } - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - return (lhs as PropertyAccessExpression).name; - case SpecialPropertyAssignmentKind.PrototypeProperty: - return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; } } else { @@ -2025,7 +2025,8 @@ namespace ts { * Symbol. */ export function hasDynamicName(declaration: Declaration): boolean { - return getNameOfDeclaration(declaration) && isDynamicName(getNameOfDeclaration(declaration)); + const name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } export function isDynamicName(name: DeclarationName): boolean { From 788b2a3dd7f082ed7efdad537400c88a314e2708 Mon Sep 17 00:00:00 2001 From: Yui T Date: Fri, 5 May 2017 16:36:02 -0700 Subject: [PATCH 104/282] Wip - remove freshness flag from jsx attributes --- src/compiler/checker.ts | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f3db3f22bf2..2d1aaedf0fc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13356,9 +13356,7 @@ namespace ts { */ function createJsxAttributesType(symbol: Symbol, attributesTable: Map) { const result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - // Spread object doesn't have freshness flag to allow excess attributes as it is very common for parent component to spread its "props" to other components in its render method. - const freshObjectLiteralFlag = spread !== emptyObjectType || compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; - result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag; + result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral; result.objectFlags |= ObjectFlags.ObjectLiteral; return result; } @@ -13877,7 +13875,30 @@ namespace ts { checkJsxAttributesAssignableToTagNameAttributes(node); } - /** + // Check if a property with the given name is known anywhere in the given type. In an object type, a property + // is considered known if the object type is empty and the check is for assignability, if the object type has + // index signatures, or if the property is actually declared in the object type. In a union or intersection + // type, a property is considered known if it is known in any constituent type. + function isKnownProperty(type: Type, name: string, isComparingJsxAttributes: boolean): boolean { + if (type.flags & TypeFlags.Object) { + const resolved = resolveStructuredTypeMembers(type); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (type.flags & TypeFlags.UnionOrIntersection) { + for (const t of (type).types) { + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } + + /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" * Check assignablity between given attributes property, "source attributes", and the "target attributes" @@ -13910,12 +13931,12 @@ namespace ts { } else { const isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); - // If sourceAttributesType has spread (e.g the type doesn't have freshness flag) after we check for assignability, we will do another pass to check that + // After we check for assignability, we will do another pass to check that // all explicitly specified attributes have correct name corresponding with target (as those will be assignable as spread type allows excess properties) // Note: if the type of these explicitly specified attributes do not match it will be an error during above assignability check. - if (isSourceAttributeTypeAssignableToTarget && sourceAttributesType !== anyType && !(sourceAttributesType.flags & TypeFlags.FreshLiteral)) { + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (const attribute of openingLikeElement.attributes.properties) { - if (isJsxAttribute(attribute) && !getPropertyOfType(targetAttributesType, attribute.name.text)) { + if (isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); } } From e43377db55ff23c43b773cce787cbe3195dfc316 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 5 May 2017 17:12:58 -0700 Subject: [PATCH 105/282] Better qualified name handling --- src/compiler/checker.ts | 42 +++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5302f43bcc7..64adede088e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2278,7 +2278,7 @@ namespace ts { result |= NodeBuilderFlags.AddUndefined; } - return result; + return result; } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { @@ -2325,7 +2325,7 @@ namespace ts { }; interface NodeBuilderContext { - readonly enclosingDeclaration: Node | undefined; + enclosingDeclaration: Node | undefined; readonly flags: NodeBuilderFlags | undefined; // State @@ -2382,7 +2382,7 @@ namespace ts { return createKeywordTypeNode(SyntaxKind.BooleanKeyword); } if (type.flags & TypeFlags.Enum) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (TypeFlags.StringLiteral)) { @@ -2396,7 +2396,7 @@ namespace ts { } if (type.flags & TypeFlags.EnumLiteral) { const parentSymbol = getParentOfSymbol(type.symbol); - const parentName = symbolToName(parentSymbol, /*expectsIdentifier*/ false, context); + const parentName = symbolToName(parentSymbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); const name = getNameOfSymbol(type.symbol, context); const enumLiteralName = createQualifiedName(parentName, name); return createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); @@ -2436,19 +2436,19 @@ namespace ts { } if (objectFlags & ObjectFlags.ClassOrInterface) { Debug.assert(!!(type.flags & TypeFlags.Object)); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); // TODO(aozgaa): handle type arguments. return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & TypeFlags.TypeParameter) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, context); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { - const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, context); + const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, /*addInElementTypeFlag*/ false); return createTypeReferenceNode(name, typeArgumentNodes); } @@ -2526,14 +2526,14 @@ namespace ts { if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, SymbolFlags.Value); } else if (contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - const entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false, context); + const entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false, SymbolFlags.Type, context); return createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -2618,8 +2618,8 @@ namespace ts { return false; } - function createTypeQueryNodeFromSymbol(symbol: Symbol) { - const entityName = symbolToName(symbol, /*expectsIdentifier*/ false, context); + function createTypeQueryNodeFromSymbol(symbol: Symbol, symbolFlags: SymbolFlags) { + const entityName = symbolToName(symbol, /*expectsIdentifier*/ false, symbolFlags, context); return createTypeQueryNode(entityName); } @@ -2665,7 +2665,7 @@ namespace ts { // the default outer type arguments), we don't show the group. if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { // inFirstTypeArgument??? - const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true, context); + const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true, SymbolFlags.Type, context); if (!qualifiedName) { qualifiedName = createQualifiedName(qualifiedNamePart, /*right*/ undefined); } @@ -2679,7 +2679,7 @@ namespace ts { } } let entityName: EntityName = undefined; - const nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true, context); + const nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true, SymbolFlags.Type, context); if (qualifiedName) { Debug.assert(!qualifiedName.right); qualifiedName.right = nameIdentifier; @@ -2717,7 +2717,10 @@ namespace ts { // TODO: make logic mirror that of writeObjectLiteralType for (const propertySymbol of properties) { const propertyType = getTypeOfSymbol(propertySymbol); - const propertyName = symbolToName(propertySymbol, /*expectsIdentifier*/ true, context); + const saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + const propertyName = symbolToName(propertySymbol, /*expectsIdentifier*/ true, SymbolFlags.Value, context); + context.enclosingDeclaration = saveEnclosingDeclaration; const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? createToken(SyntaxKind.QuestionToken) : undefined; if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length) { const signatures = getSignaturesOfType(propertyType, SignatureKind.Call); @@ -2767,7 +2770,6 @@ namespace ts { } function signatureToSignatureDeclarationHelper(signature: Signature, kind: SyntaxKind, context: NodeBuilderContext): SignatureDeclaration { - const typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter, context)); const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter, context)); if (signature.thisParameter) { @@ -2801,7 +2803,7 @@ namespace ts { const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); const defaultParameter = getDefaultFromTypeParameter(type); const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ true, context); + const name = symbolToName(type.symbol, /*expectsIdentifier*/ true, SymbolFlags.Type, context); return createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } @@ -2825,15 +2827,15 @@ namespace ts { // TODO: add meaning: SymbolFlags argument. // TODO: add SymbolFormatFlags?? Yes to add outer type parameters. Defer UseOnlyExternalAliasing until a separate symbolbuilder PR. - function symbolToName(symbol: Symbol, expectsIdentifier: true, context: NodeBuilderContext): Identifier; - function symbolToName(symbol: Symbol, expectsIdentifier: false, context: NodeBuilderContext): EntityName; - function symbolToName(symbol: Symbol, expectsIdentifier: boolean, context: NodeBuilderContext): EntityName { + function symbolToName(symbol: Symbol, expectsIdentifier: true, meaning: SymbolFlags, context: NodeBuilderContext): Identifier; + function symbolToName(symbol: Symbol, expectsIdentifier: false, meaning: SymbolFlags, context: NodeBuilderContext): EntityName; + function symbolToName(symbol: Symbol, expectsIdentifier: boolean, meaning: SymbolFlags, context: NodeBuilderContext): EntityName { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, SymbolFlags.None, /*endOfChain*/ true); + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); Debug.assert(chain && chain.length > 0); } else { From ada4b3d4d85e7d7597fcaec4e8ac9107aaa06afb Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 5 May 2017 17:38:23 -0700 Subject: [PATCH 106/282] Fix var emit order for converted loops --- src/compiler/transformers/es2015.ts | 3 +- .../baselines/reference/capturedVarInLoop.js | 17 +++++++++++ .../reference/capturedVarInLoop.symbols | 22 ++++++++++++++ .../reference/capturedVarInLoop.types | 30 +++++++++++++++++++ tests/cases/compiler/capturedVarInLoop.ts | 6 ++++ 5 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/capturedVarInLoop.js create mode 100644 tests/baselines/reference/capturedVarInLoop.symbols create mode 100644 tests/baselines/reference/capturedVarInLoop.types create mode 100644 tests/cases/compiler/capturedVarInLoop.ts diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 734fbcaeb16..be01d943412 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -2009,13 +2009,14 @@ namespace ts { } else { assignment = createBinary(decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression)); + setTextRange(assignment, decl); } assignments = append(assignments, assignment); } } if (assignments) { - updated = setTextRange(createStatement(reduceLeft(assignments, (acc, v) => createBinary(v, SyntaxKind.CommaToken, acc))), node); + updated = setTextRange(createStatement(inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted diff --git a/tests/baselines/reference/capturedVarInLoop.js b/tests/baselines/reference/capturedVarInLoop.js new file mode 100644 index 00000000000..303c18eda2d --- /dev/null +++ b/tests/baselines/reference/capturedVarInLoop.js @@ -0,0 +1,17 @@ +//// [capturedVarInLoop.ts] +for (var i = 0; i < 10; i++) { + var str = 'x', len = str.length; + let lambda1 = (y) => { }; + let lambda2 = () => lambda1(len); +} + +//// [capturedVarInLoop.js] +var _loop_1 = function () { + str = 'x', len = str.length; + var lambda1 = function (y) { }; + var lambda2 = function () { return lambda1(len); }; +}; +var str, len; +for (var i = 0; i < 10; i++) { + _loop_1(); +} diff --git a/tests/baselines/reference/capturedVarInLoop.symbols b/tests/baselines/reference/capturedVarInLoop.symbols new file mode 100644 index 00000000000..9f218154fd8 --- /dev/null +++ b/tests/baselines/reference/capturedVarInLoop.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/capturedVarInLoop.ts === +for (var i = 0; i < 10; i++) { +>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8)) +>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8)) +>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8)) + + var str = 'x', len = str.length; +>str : Symbol(str, Decl(capturedVarInLoop.ts, 1, 7)) +>len : Symbol(len, Decl(capturedVarInLoop.ts, 1, 18)) +>str.length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>str : Symbol(str, Decl(capturedVarInLoop.ts, 1, 7)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + let lambda1 = (y) => { }; +>lambda1 : Symbol(lambda1, Decl(capturedVarInLoop.ts, 2, 7)) +>y : Symbol(y, Decl(capturedVarInLoop.ts, 2, 19)) + + let lambda2 = () => lambda1(len); +>lambda2 : Symbol(lambda2, Decl(capturedVarInLoop.ts, 3, 7)) +>lambda1 : Symbol(lambda1, Decl(capturedVarInLoop.ts, 2, 7)) +>len : Symbol(len, Decl(capturedVarInLoop.ts, 1, 18)) +} diff --git a/tests/baselines/reference/capturedVarInLoop.types b/tests/baselines/reference/capturedVarInLoop.types new file mode 100644 index 00000000000..37d78df8ba3 --- /dev/null +++ b/tests/baselines/reference/capturedVarInLoop.types @@ -0,0 +1,30 @@ +=== tests/cases/compiler/capturedVarInLoop.ts === +for (var i = 0; i < 10; i++) { +>i : number +>0 : 0 +>i < 10 : boolean +>i : number +>10 : 10 +>i++ : number +>i : number + + var str = 'x', len = str.length; +>str : string +>'x' : "x" +>len : number +>str.length : number +>str : string +>length : number + + let lambda1 = (y) => { }; +>lambda1 : (y: any) => void +>(y) => { } : (y: any) => void +>y : any + + let lambda2 = () => lambda1(len); +>lambda2 : () => void +>() => lambda1(len) : () => void +>lambda1(len) : void +>lambda1 : (y: any) => void +>len : number +} diff --git a/tests/cases/compiler/capturedVarInLoop.ts b/tests/cases/compiler/capturedVarInLoop.ts new file mode 100644 index 00000000000..65cc5620f83 --- /dev/null +++ b/tests/cases/compiler/capturedVarInLoop.ts @@ -0,0 +1,6 @@ +// @target: es5 +for (var i = 0; i < 10; i++) { + var str = 'x', len = str.length; + let lambda1 = (y) => { }; + let lambda2 = () => lambda1(len); +} \ No newline at end of file From 64ea6803aad6fc07158a6b479edf3b06198a3df8 Mon Sep 17 00:00:00 2001 From: Joe Chung Date: Sat, 6 May 2017 22:11:14 -0700 Subject: [PATCH 107/282] Support @arg and @argument synonyms for @param JSDoc tag - Fix #15477 --- src/compiler/parser.ts | 2 + src/harness/unittests/jsDocParsing.ts | 12 +++++ ...parsesCorrectly.argSynonymForParamTag.json | 49 +++++++++++++++++++ ...sCorrectly.argumentSynonymForParamTag.json | 49 +++++++++++++++++++ 4 files changed, 112 insertions(+) create mode 100644 tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json create mode 100644 tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index d355ff24583..cc3fb24bdb8 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6502,6 +6502,8 @@ namespace ts { case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; diff --git a/src/harness/unittests/jsDocParsing.ts b/src/harness/unittests/jsDocParsing.ts index 98c32c77778..309e49bd6b8 100644 --- a/src/harness/unittests/jsDocParsing.ts +++ b/src/harness/unittests/jsDocParsing.ts @@ -241,6 +241,18 @@ namespace ts { */`); + parsesCorrectly("argSynonymForParamTag", +`/** + * @arg {number} name1 Description + */`); + + + parsesCorrectly("argumentSynonymForParamTag", +`/** + * @argument {number} name1 Description + */`); + + parsesCorrectly("templateTag", `/** * @template T diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json new file mode 100644 index 00000000000..064a040c58f --- /dev/null +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json @@ -0,0 +1,49 @@ +{ + "kind": "JSDocComment", + "pos": 0, + "end": 44, + "tags": { + "0": { + "kind": "JSDocParameterTag", + "pos": 8, + "end": 27, + "atToken": { + "kind": "AtToken", + "pos": 8, + "end": 9 + }, + "tagName": { + "kind": "Identifier", + "pos": 9, + "end": 12, + "text": "arg" + }, + "typeExpression": { + "kind": "JSDocTypeExpression", + "pos": 13, + "end": 21, + "type": { + "kind": "NumberKeyword", + "pos": 14, + "end": 20 + } + }, + "postParameterName": { + "kind": "Identifier", + "pos": 22, + "end": 27, + "text": "name1" + }, + "parameterName": { + "kind": "Identifier", + "pos": 22, + "end": 27, + "text": "name1" + }, + "comment": "Description" + }, + "length": 1, + "pos": 8, + "end": 27 + } +} \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json new file mode 100644 index 00000000000..264b5850223 --- /dev/null +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json @@ -0,0 +1,49 @@ +{ + "kind": "JSDocComment", + "pos": 0, + "end": 49, + "tags": { + "0": { + "kind": "JSDocParameterTag", + "pos": 8, + "end": 32, + "atToken": { + "kind": "AtToken", + "pos": 8, + "end": 9 + }, + "tagName": { + "kind": "Identifier", + "pos": 9, + "end": 17, + "text": "argument" + }, + "typeExpression": { + "kind": "JSDocTypeExpression", + "pos": 18, + "end": 26, + "type": { + "kind": "NumberKeyword", + "pos": 19, + "end": 25 + } + }, + "postParameterName": { + "kind": "Identifier", + "pos": 27, + "end": 32, + "text": "name1" + }, + "parameterName": { + "kind": "Identifier", + "pos": 27, + "end": 32, + "text": "name1" + }, + "comment": "Description" + }, + "length": 1, + "pos": 8, + "end": 32 + } +} \ No newline at end of file From c08e1fcc5d00c04ca5813e159e9b5644369227e2 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 8 May 2017 09:26:19 -0700 Subject: [PATCH 108/282] Remove check for static from checkKindsOfPropertyMemberOrderrides, which is only called on instance side --- src/compiler/checker.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d3e2233bc44..dfb1f9b832f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -20678,11 +20678,6 @@ namespace ts { continue; } - if ((baseDeclarationFlags & ModifierFlags.Static) !== (derivedDeclarationFlags & ModifierFlags.Static)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & SymbolFlags.PropertyOrAccessor && derived.flags & SymbolFlags.PropertyOrAccessor) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; From 22f353ac940bfd4e170d9e56a094fdd385476191 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 8 May 2017 09:35:21 -0700 Subject: [PATCH 109/282] Turn ClassElement and TypeElement into unions too Slows down compilation another 3%, so I'm not sure we'll want to take this change. --- src/compiler/types.ts | 75 ++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 41 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 043c8b9a0b1..4ec5c0f97bf 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -616,7 +616,6 @@ namespace ts { | CallExpression | CallSignatureDeclaration | ClassDeclaration - | ClassElement | ClassExpression | ClassLikeDeclaration | ConstructSignatureDeclaration @@ -717,13 +716,14 @@ namespace ts { typeParameters?: NodeArray; parameters: NodeArray; type?: TypeNode; + questionToken?: QuestionToken; } - export interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + export interface CallSignatureDeclaration extends SignatureDeclaration { kind: SyntaxKind.CallSignature; } - export interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + export interface ConstructSignatureDeclaration extends SignatureDeclaration { kind: SyntaxKind.ConstructSignature; } @@ -762,7 +762,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface PropertySignature extends TypeElement { + export interface PropertySignature extends DeclarationBase { kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; // Declared property name questionToken?: QuestionToken; // Present on optional property @@ -770,7 +770,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface PropertyDeclaration extends ClassElement { + export interface PropertyDeclaration extends DeclarationBase { kind: SyntaxKind.PropertyDeclaration; questionToken?: QuestionToken; // Present for use with reporting a grammar error name: PropertyName; @@ -876,7 +876,7 @@ namespace ts { body?: FunctionBody; } - export interface MethodSignature extends SignatureDeclaration, TypeElement { + export interface MethodSignature extends SignatureDeclaration { kind: SyntaxKind.MethodSignature; name: PropertyName; } @@ -890,27 +890,28 @@ namespace ts { // Because of this, it may be necessary to determine what sort of MethodDeclaration you have // at later stages of the compiler pipeline. In that case, you can either check the parent kind // of the method, or use helpers like isObjectLiteralMethodDeclaration - export interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + export interface MethodDeclaration extends FunctionLikeDeclaration, ObjectLiteralElement { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - export interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + export interface ConstructorDeclaration extends FunctionLikeDeclaration { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ - export interface SemicolonClassElement extends ClassElement { + export interface SemicolonClassElement extends DeclarationBase { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; + name?: PropertyName; } // See the comment on MethodDeclaration for the intuition behind GetAccessorDeclaration being a // ClassElement and an ObjectLiteralElement. - export interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + export interface GetAccessorDeclaration extends FunctionLikeDeclaration, ObjectLiteralElement { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; @@ -919,7 +920,7 @@ namespace ts { // See the comment on MethodDeclaration for the intuition behind SetAccessorDeclaration being a // ClassElement and an ObjectLiteralElement. - export interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + export interface SetAccessorDeclaration extends FunctionLikeDeclaration, ObjectLiteralElement { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; @@ -928,7 +929,7 @@ namespace ts { export type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; - export interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { + export interface IndexSignatureDeclaration extends SignatureDeclaration { kind: SyntaxKind.IndexSignature; parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; } @@ -1695,7 +1696,7 @@ namespace ts { kind: SyntaxKind.DebuggerStatement; } - export interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + export interface MissingDeclaration extends DeclarationStatement, ObjectLiteralElement { kind: SyntaxKind.MissingDeclaration; name?: Identifier; } @@ -1863,34 +1864,26 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export interface ClassElement extends DeclarationBase { - kind: - | SyntaxKind.PropertyDeclaration - | SyntaxKind.MethodDeclaration - | SyntaxKind.Constructor - | SyntaxKind.SemicolonClassElement - | SyntaxKind.GetAccessor - | SyntaxKind.SetAccessor - | SyntaxKind.IndexSignature - | SyntaxKind.MissingDeclaration; - _classElementBrand: any; - name?: PropertyName; - } + export type ClassElement = + | PropertyDeclaration + | MethodDeclaration + | ConstructorDeclaration + | SemicolonClassElement + | GetAccessorDeclaration + | SetAccessorDeclaration + | IndexSignatureDeclaration + | MissingDeclaration; - export interface TypeElement extends DeclarationBase { - kind: - | SyntaxKind.CallSignature - | SyntaxKind.ConstructSignature - | SyntaxKind.PropertySignature - | SyntaxKind.MethodSignature - | SyntaxKind.IndexSignature - | SyntaxKind.MissingDeclaration - | SyntaxKind.JSDocPropertyTag - | SyntaxKind.JSDocRecordMember; - _typeElementBrand: any; - name?: PropertyName; - questionToken?: QuestionToken; - } + export type TypeElement = + | CallSignatureDeclaration + | ConstructSignatureDeclaration + | PropertySignature + | MethodSignature + | IndexSignatureDeclaration + | MissingDeclaration + | IndexSignatureDeclaration + | JSDocPropertyTag + | JSDocRecordMember; export interface InterfaceDeclaration extends DeclarationStatement { kind: SyntaxKind.InterfaceDeclaration; @@ -2224,7 +2217,7 @@ namespace ts { jsDocTypeLiteral?: JSDocTypeLiteral; } - export interface JSDocPropertyTag extends JSDocTag, TypeElement { + export interface JSDocPropertyTag extends JSDocTag { kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; From 2c5117b2d94ea44b8d8631bc3958eb6020348f94 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Mon, 8 May 2017 09:46:46 -0700 Subject: [PATCH 110/282] Refactor "isKnownProperty" to be use outside of checkTypeScriptAssignable as JSX do excess property after --- src/compiler/checker.ts | 58 +++++++++++++++-------------------------- 1 file changed, 21 insertions(+), 37 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2d1aaedf0fc..fd2e18e7dd9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8688,29 +8688,6 @@ namespace ts { return Ternary.False; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type: Type, name: string, isComparingJsxAttributes: boolean): boolean { - if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & TypeFlags.UnionOrIntersection) { - for (const t of (type).types) { - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } - function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { if (maybeTypeOfKind(target, TypeFlags.Object) && !(getObjectFlags(target) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) { const isComparingJsxAttributes = !!(source.flags & TypeFlags.JsxAttributes); @@ -13875,21 +13852,26 @@ namespace ts { checkJsxAttributesAssignableToTagNameAttributes(node); } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type: Type, name: string, isComparingJsxAttributes: boolean): boolean { - if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType: Type, name: string, isComparingJsxAttributes: boolean): boolean { + if (targetType.flags & TypeFlags.Object) { + const resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. return true; } } - else if (type.flags & TypeFlags.UnionOrIntersection) { - for (const t of (type).types) { + else if (targetType.flags & TypeFlags.UnionOrIntersection) { + for (const t of (targetType).types) { if (isKnownProperty(t, name, isComparingJsxAttributes)) { return true; } @@ -13898,7 +13880,7 @@ namespace ts { return false; } - /** + /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" * Check assignablity between given attributes property, "source attributes", and the "target attributes" @@ -13930,14 +13912,16 @@ namespace ts { error(openingLikeElement, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties const isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); - // After we check for assignability, we will do another pass to check that - // all explicitly specified attributes have correct name corresponding with target (as those will be assignable as spread type allows excess properties) - // Note: if the type of these explicitly specified attributes do not match it will be an error during above assignability check. + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (const attribute of openingLikeElement.attributes.properties) { if (isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; } } } From 1e32b1097c65c6dae2a1234256f2e31176e37597 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Mon, 8 May 2017 09:46:54 -0700 Subject: [PATCH 111/282] Update baselines --- ...StringLiteralsInJsxAttributes02.errors.txt | 14 +++++------ .../tsxAttributeResolution1.errors.txt | 18 +++++--------- .../tsxAttributeResolution11.errors.txt | 6 ++--- .../tsxAttributeResolution15.errors.txt | 6 ++--- .../tsxElementResolution11.errors.txt | 6 ++--- .../tsxElementResolution3.errors.txt | 4 ++-- .../tsxElementResolution4.errors.txt | 4 ++-- ...ponentWithDefaultTypeParameter3.errors.txt | 14 ++++------- ...elessFunctionComponentOverload4.errors.txt | 22 ++++++++++++----- ...elessFunctionComponentOverload5.errors.txt | 6 +++-- ...tsxStatelessFunctionComponents1.errors.txt | 24 ++++++++----------- ...tsxStatelessFunctionComponents2.errors.txt | 6 ++--- .../reference/tsxUnionElementType4.errors.txt | 12 ++++------ .../reference/tsxUnionElementType6.errors.txt | 6 ++--- 14 files changed, 66 insertions(+), 82 deletions(-) diff --git a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt index 63686e29419..ccf56532bc4 100644 --- a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt +++ b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt @@ -2,10 +2,10 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,24): err Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,24): error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. + Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'. + Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,43): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,24): error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,36): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,65): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. @@ -45,14 +45,14 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): err const b2 = {console.log(k)}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. +!!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'. +!!! error TS2322: Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'. const b3 = ; // goTo has type"home" | "contact" ~~~~~ !!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. const b4 = ; // goTo has type "home" | "contact" - ~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. export function NoOverload(buttonProps: ButtonProps): JSX.Element { return undefined } const c1 = {console.log(k)}}} extra />; // k has type any diff --git a/tests/baselines/reference/tsxAttributeResolution1.errors.txt b/tests/baselines/reference/tsxAttributeResolution1.errors.txt index d064f72f85d..f6c84f80fa5 100644 --- a/tests/baselines/reference/tsxAttributeResolution1.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution1.errors.txt @@ -1,15 +1,12 @@ tests/cases/conformance/jsx/file.tsx(23,8): error TS2322: Type '{ x: "0"; }' is not assignable to type 'Attribs1'. Types of property 'x' are incompatible. Type '"0"' is not assignable to type 'number'. -tests/cases/conformance/jsx/file.tsx(24,8): error TS2322: Type '{ y: 0; }' is not assignable to type 'Attribs1'. - Property 'y' does not exist on type 'Attribs1'. -tests/cases/conformance/jsx/file.tsx(25,8): error TS2322: Type '{ y: "foo"; }' is not assignable to type 'Attribs1'. - Property 'y' does not exist on type 'Attribs1'. +tests/cases/conformance/jsx/file.tsx(24,8): error TS2339: Property 'y' does not exist on type 'Attribs1'. +tests/cases/conformance/jsx/file.tsx(25,8): error TS2339: Property 'y' does not exist on type 'Attribs1'. tests/cases/conformance/jsx/file.tsx(26,8): error TS2322: Type '{ x: "32"; }' is not assignable to type 'Attribs1'. Types of property 'x' are incompatible. Type '"32"' is not assignable to type 'number'. -tests/cases/conformance/jsx/file.tsx(27,8): error TS2322: Type '{ var: "10"; }' is not assignable to type 'Attribs1'. - Property 'var' does not exist on type 'Attribs1'. +tests/cases/conformance/jsx/file.tsx(27,8): error TS2339: Property 'var' does not exist on type 'Attribs1'. tests/cases/conformance/jsx/file.tsx(29,1): error TS2322: Type '{}' is not assignable to type '{ reqd: string; }'. Property 'reqd' is missing in type '{}'. tests/cases/conformance/jsx/file.tsx(30,8): error TS2322: Type '{ reqd: 10; }' is not assignable to type '{ reqd: string; }'. @@ -47,12 +44,10 @@ tests/cases/conformance/jsx/file.tsx(30,8): error TS2322: Type '{ reqd: 10; }' i !!! error TS2322: Type '"0"' is not assignable to type 'number'. ; // Error, no property "y" ~~~~~ -!!! error TS2322: Type '{ y: 0; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'y' does not exist on type 'Attribs1'. +!!! error TS2339: Property 'y' does not exist on type 'Attribs1'. ; // Error, no property "y" ~~~~~~~ -!!! error TS2322: Type '{ y: "foo"; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'y' does not exist on type 'Attribs1'. +!!! error TS2339: Property 'y' does not exist on type 'Attribs1'. ; // Error, "32" is not number ~~~~~~ !!! error TS2322: Type '{ x: "32"; }' is not assignable to type 'Attribs1'. @@ -60,8 +55,7 @@ tests/cases/conformance/jsx/file.tsx(30,8): error TS2322: Type '{ reqd: 10; }' i !!! error TS2322: Type '"32"' is not assignable to type 'number'. ; // Error, no 'var' property ~~~~~~~~ -!!! error TS2322: Type '{ var: "10"; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'var' does not exist on type 'Attribs1'. +!!! error TS2339: Property 'var' does not exist on type 'Attribs1'. ; // Error, missing reqd ~~~~~~~~~ diff --git a/tests/baselines/reference/tsxAttributeResolution11.errors.txt b/tests/baselines/reference/tsxAttributeResolution11.errors.txt index 08a75c3b8bb..907b9bce776 100644 --- a/tests/baselines/reference/tsxAttributeResolution11.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution11.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(11,22): error TS2322: Type '{ bar: "world"; }' is not assignable to type 'IntrinsicAttributes & { ref?: string; }'. - Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. +tests/cases/conformance/jsx/file.tsx(11,22): error TS2339: Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. ==== tests/cases/conformance/jsx/react.d.ts (0 errors) ==== @@ -28,7 +27,6 @@ tests/cases/conformance/jsx/file.tsx(11,22): error TS2322: Type '{ bar: "world"; // Should be an OK var x = ; ~~~~~~~~~~~ -!!! error TS2322: Type '{ bar: "world"; }' is not assignable to type 'IntrinsicAttributes & { ref?: string; }'. -!!! error TS2322: Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. +!!! error TS2339: Property 'bar' does not exist on type 'IntrinsicAttributes & { ref?: string; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxAttributeResolution15.errors.txt b/tests/baselines/reference/tsxAttributeResolution15.errors.txt index 870599acd27..2ab79ea7aae 100644 --- a/tests/baselines/reference/tsxAttributeResolution15.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution15.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(11,21): error TS2322: Type '{ prop1: "hello"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(11,21): error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -15,8 +14,7 @@ tests/cases/conformance/jsx/file.tsx(11,21): error TS2322: Type '{ prop1: "hello // Error let a = ~~~~~~~~~~~~~ -!!! error TS2322: Type '{ prop1: "hello"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +!!! error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. // OK let b = { this.textInput = input; }} /> diff --git a/tests/baselines/reference/tsxElementResolution11.errors.txt b/tests/baselines/reference/tsxElementResolution11.errors.txt index f0d5cf1e009..878f5a8b337 100644 --- a/tests/baselines/reference/tsxElementResolution11.errors.txt +++ b/tests/baselines/reference/tsxElementResolution11.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(17,7): error TS2322: Type '{ x: 10; }' is not assignable to type '{ q?: number; }'. - Property 'x' does not exist on type '{ q?: number; }'. +tests/cases/conformance/jsx/file.tsx(17,7): error TS2339: Property 'x' does not exist on type '{ q?: number; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -21,8 +20,7 @@ tests/cases/conformance/jsx/file.tsx(17,7): error TS2322: Type '{ x: 10; }' is n var Obj2: Obj2type; ; // Error ~~~~~~ -!!! error TS2322: Type '{ x: 10; }' is not assignable to type '{ q?: number; }'. -!!! error TS2322: Property 'x' does not exist on type '{ q?: number; }'. +!!! error TS2339: Property 'x' does not exist on type '{ q?: number; }'. interface Obj3type { new(n: string): { x: number; }; diff --git a/tests/baselines/reference/tsxElementResolution3.errors.txt b/tests/baselines/reference/tsxElementResolution3.errors.txt index d869821a4cb..4e7687c94e2 100644 --- a/tests/baselines/reference/tsxElementResolution3.errors.txt +++ b/tests/baselines/reference/tsxElementResolution3.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/jsx/file.tsx(12,7): error TS2322: Type '{ w: "err"; }' is not assignable to type '{ n: string; }'. - Property 'w' does not exist on type '{ n: string; }'. + Property 'n' is missing in type '{ w: "err"; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -17,4 +17,4 @@ tests/cases/conformance/jsx/file.tsx(12,7): error TS2322: Type '{ w: "err"; }' i ; ~~~~~~~ !!! error TS2322: Type '{ w: "err"; }' is not assignable to type '{ n: string; }'. -!!! error TS2322: Property 'w' does not exist on type '{ n: string; }'. \ No newline at end of file +!!! error TS2322: Property 'n' is missing in type '{ w: "err"; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxElementResolution4.errors.txt b/tests/baselines/reference/tsxElementResolution4.errors.txt index b5d5437d872..461cfe025df 100644 --- a/tests/baselines/reference/tsxElementResolution4.errors.txt +++ b/tests/baselines/reference/tsxElementResolution4.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/jsx/file.tsx(16,7): error TS2322: Type '{ q: ""; }' is not assignable to type '{ m: string; }'. - Property 'q' does not exist on type '{ m: string; }'. + Property 'm' is missing in type '{ q: ""; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -21,5 +21,5 @@ tests/cases/conformance/jsx/file.tsx(16,7): error TS2322: Type '{ q: ""; }' is n ; ~~~~ !!! error TS2322: Type '{ q: ""; }' is not assignable to type '{ m: string; }'. -!!! error TS2322: Property 'q' does not exist on type '{ m: string; }'. +!!! error TS2322: Property 'm' is missing in type '{ q: ""; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt b/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt index c49bd643537..230ca1e2795 100644 --- a/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt +++ b/tests/baselines/reference/tsxReactComponentWithDefaultTypeParameter3.errors.txt @@ -1,7 +1,5 @@ -tests/cases/conformance/jsx/file.tsx(16,17): error TS2322: Type '{ a: 10; b: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. - Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. -tests/cases/conformance/jsx/file.tsx(17,18): error TS2322: Type '{ a: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. - Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(16,17): error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(17,18): error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. ==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== @@ -21,10 +19,8 @@ tests/cases/conformance/jsx/file.tsx(17,18): error TS2322: Type '{ a: "hi"; }' i // Error let x = - ~~~~~~~~~~~~~ -!!! error TS2322: Type '{ a: 10; b: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. -!!! error TS2322: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + ~~~~~~ +!!! error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. let x2 = ~~~~~~ -!!! error TS2322: Type '{ a: "hi"; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. -!!! error TS2322: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. \ No newline at end of file +!!! error TS2339: Property 'a' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt index c7f1b03f6aa..4f717bfca96 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload4.errors.txt @@ -1,5 +1,6 @@ tests/cases/conformance/jsx/file.tsx(12,22): error TS2322: Type '{ extraProp: true; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. - Property 'extraProp' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. + Type '{ extraProp: true; }' is not assignable to type '{ yy: number; yy1: string; }'. + Property 'yy' is missing in type '{ extraProp: true; }'. tests/cases/conformance/jsx/file.tsx(13,22): error TS2322: Type '{ yy: 10; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. Type '{ yy: 10; }' is not assignable to type '{ yy: number; yy1: string; }'. Property 'yy1' is missing in type '{ yy: 10; }'. @@ -28,9 +29,13 @@ tests/cases/conformance/jsx/file.tsx(34,29): error TS2322: Type '{ y1: "hello"; Types of property 'y1' are incompatible. Type '"hello"' is not assignable to type 'boolean'. tests/cases/conformance/jsx/file.tsx(35,29): error TS2322: Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. - Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. + Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. + Types of property 'y1' are incompatible. + Type '"hello"' is not assignable to type 'boolean'. tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. - Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. + Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. + Types of property 'y1' are incompatible. + Type '"hello"' is not assignable to type 'boolean'. ==== tests/cases/conformance/jsx/file.tsx (11 errors) ==== @@ -48,7 +53,8 @@ tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; const c0 = ; // extra property; ~~~~~~~~~ !!! error TS2322: Type '{ extraProp: true; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. -!!! error TS2322: Property 'extraProp' does not exist on type 'IntrinsicAttributes & { yy: number; yy1: string; }'. +!!! error TS2322: Type '{ extraProp: true; }' is not assignable to type '{ yy: number; yy1: string; }'. +!!! error TS2322: Property 'yy' is missing in type '{ extraProp: true; }'. const c1 = ; // missing property; ~~~~~~~ !!! error TS2322: Type '{ yy: 10; }' is not assignable to type 'IntrinsicAttributes & { yy: number; yy1: string; }'. @@ -109,9 +115,13 @@ tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type '{ y1: "hello"; const e3 = ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. -!!! error TS2322: Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: "hi"; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Types of property 'y1' are incompatible. +!!! error TS2322: Type '"hello"' is not assignable to type 'boolean'. const e4 = Hi ~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. -!!! error TS2322: Property 'children' does not exist on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Type '{ y1: "hello"; y2: 1000; children: string; }' is not assignable to type '{ y1: boolean; y2?: number; y3: boolean; }'. +!!! error TS2322: Types of property 'y1' are incompatible. +!!! error TS2322: Type '"hello"' is not assignable to type 'boolean'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt index 7c5aa3daa36..b7e4fc78e0e 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt @@ -1,5 +1,6 @@ tests/cases/conformance/jsx/file.tsx(48,24): error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. - Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. + Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'HyphenProps'. + Property '"data-format"' is missing in type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }'. tests/cases/conformance/jsx/file.tsx(49,24): error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'HyphenProps'. Property '"data-format"' is missing in type '{ to: string; onClick: (e: any) => void; children: string; }'. @@ -75,7 +76,8 @@ tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type '{ data-format: const b0 = {}}>GO; // extra property; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. -!!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }' is not assignable to type 'HyphenProps'. +!!! error TS2322: Property '"data-format"' is missing in type '{ to: "/some/path"; onClick: (e: MouseEvent) => void; children: string; }'. const b1 = {}} {...obj0}>Hello world; // extra property; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ to: string; onClick: (e: any) => void; children: string; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt index 1f2c00c73d1..243f29493bf 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponents1.errors.txt @@ -1,18 +1,16 @@ tests/cases/conformance/jsx/file.tsx(19,16): error TS2322: Type '{ naaame: "world"; }' is not assignable to type 'IntrinsicAttributes & { name: string; }'. - Property 'naaame' does not exist on type 'IntrinsicAttributes & { name: string; }'. + Type '{ naaame: "world"; }' is not assignable to type '{ name: string; }'. + Property 'name' is missing in type '{ naaame: "world"; }'. tests/cases/conformance/jsx/file.tsx(27,15): error TS2322: Type '{ name: 42; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. Type '{ name: 42; }' is not assignable to type '{ name?: string; }'. Types of property 'name' are incompatible. Type '42' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(29,15): error TS2322: Type '{ naaaaaaame: "no"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. - Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +tests/cases/conformance/jsx/file.tsx(29,15): error TS2339: Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. tests/cases/conformance/jsx/file.tsx(34,23): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { "prop-name": string; }'. Type '{}' is not assignable to type '{ "prop-name": string; }'. Property '"prop-name"' is missing in type '{}'. -tests/cases/conformance/jsx/file.tsx(37,23): error TS2322: Type '{ prop1: true; }' is not assignable to type 'IntrinsicAttributes'. - Property 'prop1' does not exist on type 'IntrinsicAttributes'. -tests/cases/conformance/jsx/file.tsx(38,24): error TS2322: Type '{ ref: (x: any) => any; }' is not assignable to type 'IntrinsicAttributes'. - Property 'ref' does not exist on type 'IntrinsicAttributes'. +tests/cases/conformance/jsx/file.tsx(37,23): error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes'. +tests/cases/conformance/jsx/file.tsx(38,24): error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes'. tests/cases/conformance/jsx/file.tsx(41,16): error TS1005: ',' expected. @@ -38,7 +36,8 @@ tests/cases/conformance/jsx/file.tsx(41,16): error TS1005: ',' expected. let b = ; ~~~~~~~~~~~~~~ !!! error TS2322: Type '{ naaame: "world"; }' is not assignable to type 'IntrinsicAttributes & { name: string; }'. -!!! error TS2322: Property 'naaame' does not exist on type 'IntrinsicAttributes & { name: string; }'. +!!! error TS2322: Type '{ naaame: "world"; }' is not assignable to type '{ name: string; }'. +!!! error TS2322: Property 'name' is missing in type '{ naaame: "world"; }'. // OK let c = ; @@ -55,8 +54,7 @@ tests/cases/conformance/jsx/file.tsx(41,16): error TS1005: ',' expected. // Error let f = ; ~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ naaaaaaame: "no"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. -!!! error TS2322: Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +!!! error TS2339: Property 'naaaaaaame' does not exist on type 'IntrinsicAttributes & { name?: string; }'. // OK let g = ; @@ -70,12 +68,10 @@ tests/cases/conformance/jsx/file.tsx(41,16): error TS1005: ',' expected. // Error let i = ~~~~~ -!!! error TS2322: Type '{ prop1: true; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'prop1' does not exist on type 'IntrinsicAttributes'. +!!! error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes'. let i1 = x.greeting.substr(10)} /> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ ref: (x: any) => any; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'ref' does not exist on type 'IntrinsicAttributes'. +!!! error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes'. let o = { prop1: true; diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt index 275017ecd82..00e2c4a526c 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponents2.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(19,16): error TS2322: Type '{ ref: "myRef"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. - Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +tests/cases/conformance/jsx/file.tsx(19,16): error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. tests/cases/conformance/jsx/file.tsx(25,42): error TS2339: Property 'subtr' does not exist on type 'string'. tests/cases/conformance/jsx/file.tsx(27,33): error TS2339: Property 'notARealProperty' does not exist on type 'BigGreeter'. tests/cases/conformance/jsx/file.tsx(35,26): error TS2339: Property 'propertyNotOnHtmlDivElement' does not exist on type 'HTMLDivElement'. @@ -26,8 +25,7 @@ tests/cases/conformance/jsx/file.tsx(35,26): error TS2339: Property 'propertyNot // Error - not allowed to specify 'ref' on SFCs let c = ; ~~~~~~~~~~~ -!!! error TS2322: Type '{ ref: "myRef"; }' is not assignable to type 'IntrinsicAttributes & { name?: string; }'. -!!! error TS2322: Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. +!!! error TS2339: Property 'ref' does not exist on type 'IntrinsicAttributes & { name?: string; }'. // OK - ref is valid for classes diff --git a/tests/baselines/reference/tsxUnionElementType4.errors.txt b/tests/baselines/reference/tsxUnionElementType4.errors.txt index 7c94a08b6ef..4658b566cc7 100644 --- a/tests/baselines/reference/tsxUnionElementType4.errors.txt +++ b/tests/baselines/reference/tsxUnionElementType4.errors.txt @@ -3,10 +3,8 @@ tests/cases/conformance/jsx/file.tsx(32,17): error TS2322: Type '{ x: true; }' i Type '{ x: true; }' is not assignable to type '{ x: string; }'. Types of property 'x' are incompatible. Type 'true' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(33,21): error TS2322: Type '{ x: 10; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -tests/cases/conformance/jsx/file.tsx(34,22): error TS2322: Type '{ prop: true; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. - Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(33,21): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(34,22): error TS2339: Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. ==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== @@ -50,10 +48,8 @@ tests/cases/conformance/jsx/file.tsx(34,22): error TS2322: Type '{ prop: true; } !!! error TS2322: Type 'true' is not assignable to type 'string'. let b = ~~~~~~ -!!! error TS2322: Type '{ x: 10; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. let c = ; ~~~~ -!!! error TS2322: Type '{ prop: true; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. -!!! error TS2322: Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +!!! error TS2339: Property 'prop' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxUnionElementType6.errors.txt b/tests/baselines/reference/tsxUnionElementType6.errors.txt index 1f31fb21f26..cac96565b80 100644 --- a/tests/baselines/reference/tsxUnionElementType6.errors.txt +++ b/tests/baselines/reference/tsxUnionElementType6.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(18,23): error TS2322: Type '{ x: true; }' is not assignable to type 'IntrinsicAttributes'. - Property 'x' does not exist on type 'IntrinsicAttributes'. +tests/cases/conformance/jsx/file.tsx(18,23): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes'. tests/cases/conformance/jsx/file.tsx(19,27): error TS2322: Type '{ x: "hi"; }' is not assignable to type 'IntrinsicAttributes & { x: boolean; }'. Type '{ x: "hi"; }' is not assignable to type '{ x: boolean; }'. Types of property 'x' are incompatible. @@ -32,8 +31,7 @@ tests/cases/conformance/jsx/file.tsx(21,27): error TS2322: Type '{}' is not assi // Error let a = ; ~ -!!! error TS2322: Type '{ x: true; }' is not assignable to type 'IntrinsicAttributes'. -!!! error TS2322: Property 'x' does not exist on type 'IntrinsicAttributes'. +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes'. let b = ; ~~~~~~ !!! error TS2322: Type '{ x: "hi"; }' is not assignable to type 'IntrinsicAttributes & { x: boolean; }'. From 9e03d42fda96f22e113c3b439495c814fdc735a0 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 8 May 2017 10:33:48 -0700 Subject: [PATCH 112/282] In addStringLiteralCompletionsFromType, use getBaseConstraintOfType instead of getApparentType --- src/compiler/checker.ts | 3 ++- src/compiler/types.ts | 1 + src/services/completions.ts | 2 +- tests/cases/fourslash/completionsKeyof.ts | 17 +++++++++++++++++ 4 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/completionsKeyof.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d3e2233bc44..64e45f2a905 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -204,7 +204,8 @@ namespace ts { // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType + getApparentType, + getBaseConstraintOfType, }; const tupleTypes: GenericType[] = []; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e85f4c8c476..afebdfd7bcd 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2552,6 +2552,7 @@ namespace ts { tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + /* @internal */ getBaseConstraintOfType(type: Type): Type; /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol; diff --git a/src/services/completions.ts b/src/services/completions.ts index 6ac3762b4c7..3ec936d282f 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -260,7 +260,7 @@ namespace ts.Completions { function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker): void { if (type && type.flags & TypeFlags.TypeParameter) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; diff --git a/tests/cases/fourslash/completionsKeyof.ts b/tests/cases/fourslash/completionsKeyof.ts new file mode 100644 index 00000000000..e3beae556c5 --- /dev/null +++ b/tests/cases/fourslash/completionsKeyof.ts @@ -0,0 +1,17 @@ +/// + +////interface A { a: number; }; +////interface B { a: number; b: number; }; +////function f(key: T) {} +////f("/*f*/"); +////function g(key: T) {} +////g("/*g*/"); + +goTo.marker("f"); +verify.completionListCount(1); +verify.completionListContains("a"); + +goTo.marker("g"); +verify.completionListCount(2); +verify.completionListContains("a"); +verify.completionListContains("b"); From 6038ea09c9e80972ac37817dd69044e8bd187f30 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 8 May 2017 10:40:24 -0700 Subject: [PATCH 113/282] Simplify JS check in index constraint error reporting Any declaration that is a BinaryExpression is a special javascript declaration, and all JS declarations that are checked for index constraint compatibility are, in fact, relevant. --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d3e2233bc44..a93585156bb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -20339,7 +20339,7 @@ namespace ts { // this allows to rule out cases when both property and indexer are inherited from the base class let errorNode: Node; if (propDeclaration && - (getSpecialPropertyAssignmentKind(propDeclaration as BinaryExpression) === SpecialPropertyAssignmentKind.ThisProperty || + (propDeclaration.kind === SyntaxKind.BinaryExpression || propDeclaration.name.kind === SyntaxKind.ComputedPropertyName || prop.parent === containingType.symbol)) { errorNode = propDeclaration; From 5ad2ced0c345141272ea101656d1b0ba45411884 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 8 May 2017 11:03:41 -0700 Subject: [PATCH 114/282] Update test with trickier case from #15616 --- ...aintOfJavascriptClassExpression.errors.txt | 42 +++++++++++++++++++ ...exConstraintOfJavascriptClassExpression.js | 32 -------------- ...exConstraintOfJavascriptClassExpression.ts | 8 ++++ 3 files changed, 50 insertions(+), 32 deletions(-) create mode 100644 tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt delete mode 100644 tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt new file mode 100644 index 00000000000..f648f52bb58 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt @@ -0,0 +1,42 @@ +tests/cases/compiler/weird.js(1,1): error TS2304: Cannot find name 'someFunction'. +tests/cases/compiler/weird.js(1,23): error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. +tests/cases/compiler/weird.js(4,17): error TS8009: 'const' can only be used in a .ts file. +tests/cases/compiler/weird.js(4,17): error TS1248: A class member cannot have the 'const' keyword. +tests/cases/compiler/weird.js(5,3): error TS2377: Constructors for derived classes must contain a 'super' call. +tests/cases/compiler/weird.js(6,4): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. +tests/cases/compiler/weird.js(8,25): error TS7006: Parameter 'error' implicitly has an 'any' type. +tests/cases/compiler/weird.js(9,54): error TS2663: Cannot find name 'DEFAULT_MESSAGE'. Did you mean the instance member 'this.DEFAULT_MESSAGE'? + + +==== tests/cases/compiler/weird.js (8 errors) ==== + someFunction(function(BaseClass) { + ~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'someFunction'. + ~~~~~~~~~ +!!! error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. + 'use strict'; + class Hello extends BaseClass { + const DEFAULT_MESSAGE = "nop!"; + ~~~~~ +!!! error TS8009: 'const' can only be used in a .ts file. + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS1248: A class member cannot have the 'const' keyword. + constructor() { + ~~~~~~~~~~~~~~~ + this.foo = "bar"; + ~~~~~~~~~~~~~~~~~~~~ + ~~~~ +!!! error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. + } + ~~~ +!!! error TS2377: Constructors for derived classes must contain a 'super' call. + _render(error) { + ~~~~~ +!!! error TS7006: Parameter 'error' implicitly has an 'any' type. + const message = error.message || DEFAULT_MESSAGE; + ~~~~~~~~~~~~~~~ +!!! error TS2663: Cannot find name 'DEFAULT_MESSAGE'. Did you mean the instance member 'this.DEFAULT_MESSAGE'? + } + } + }); + \ No newline at end of file diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js deleted file mode 100644 index a23461a1b58..00000000000 --- a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.js +++ /dev/null @@ -1,32 +0,0 @@ -//// [weird.js] -someFunction(function(BaseClass) { - class Hello extends BaseClass { - constructor() { - this.foo = "bar"; - } - } -}); - - -//// [foo.js] -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -someFunction(function (BaseClass) { - var Hello = (function (_super) { - __extends(Hello, _super); - function Hello() { - var _this = this; - _this.foo = "bar"; - return _this; - } - return Hello; - }(BaseClass)); -}); diff --git a/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts index 8de18a69536..51af2b276a2 100644 --- a/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts +++ b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts @@ -1,10 +1,18 @@ // @Filename: weird.js // @allowJs: true +// @checkJs: true +// @strict: true +// @noEmit: true // @out: foo.js someFunction(function(BaseClass) { + 'use strict'; class Hello extends BaseClass { + const DEFAULT_MESSAGE = "nop!"; constructor() { this.foo = "bar"; } + _render(error) { + const message = error.message || DEFAULT_MESSAGE; + } } }); From 965b98f6cbaa7c23246a3bb59d5d707bd6b5164e Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 8 May 2017 11:10:47 -0700 Subject: [PATCH 115/282] `UseFullyQualifiedType` --- src/compiler/checker.ts | 2 +- src/compiler/types.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 64adede088e..8a84fe42515 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2834,7 +2834,7 @@ namespace ts { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - if (!isTypeParameter && context.enclosingDeclaration) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType)) { chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); Debug.assert(chain && chain.length > 0); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 48c4b2cd4ac..6c1861a5892 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2571,7 +2571,6 @@ namespace ts { WriteOwnNameForAnyLike = 1 << 4, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) // TODO WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature - // TODO UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) // TODO UseTypeAliasValue = 1 << 7, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. From 883ccaee5f5201c2154381c1941485ae675bbe4a Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 8 May 2017 11:29:52 -0700 Subject: [PATCH 116/282] Remove old commented-out code from signatureHelp --- src/services/signatureHelp.ts | 162 ---------------------------------- 1 file changed, 162 deletions(-) diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 7c4f8fb016d..b250ad49467 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -1,168 +1,6 @@ /// /* @internal */ namespace ts.SignatureHelp { - - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foo Date: Mon, 8 May 2017 11:36:30 -0700 Subject: [PATCH 117/282] Clean up test a little --- ...aintOfJavascriptClassExpression.errors.txt | 45 +++++++------------ ...exConstraintOfJavascriptClassExpression.ts | 21 ++++----- 2 files changed, 27 insertions(+), 39 deletions(-) diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt index f648f52bb58..d90e6d506ff 100644 --- a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt @@ -1,42 +1,29 @@ tests/cases/compiler/weird.js(1,1): error TS2304: Cannot find name 'someFunction'. tests/cases/compiler/weird.js(1,23): error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. -tests/cases/compiler/weird.js(4,17): error TS8009: 'const' can only be used in a .ts file. -tests/cases/compiler/weird.js(4,17): error TS1248: A class member cannot have the 'const' keyword. -tests/cases/compiler/weird.js(5,3): error TS2377: Constructors for derived classes must contain a 'super' call. -tests/cases/compiler/weird.js(6,4): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. -tests/cases/compiler/weird.js(8,25): error TS7006: Parameter 'error' implicitly has an 'any' type. -tests/cases/compiler/weird.js(9,54): error TS2663: Cannot find name 'DEFAULT_MESSAGE'. Did you mean the instance member 'this.DEFAULT_MESSAGE'? +tests/cases/compiler/weird.js(6,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly has an 'any' type. -==== tests/cases/compiler/weird.js (8 errors) ==== +==== tests/cases/compiler/weird.js (4 errors) ==== someFunction(function(BaseClass) { ~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'someFunction'. ~~~~~~~~~ !!! error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. - 'use strict'; - class Hello extends BaseClass { - const DEFAULT_MESSAGE = "nop!"; + 'use strict'; + const DEFAULT_MESSAGE = "nop!"; + class Hello extends BaseClass { + constructor() { + super(); + ~~~~~~~ +!!! error TS2346: Supplied parameters do not match any signature of call target. + this.foo = "bar"; + } + _render(error) { ~~~~~ -!!! error TS8009: 'const' can only be used in a .ts file. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1248: A class member cannot have the 'const' keyword. - constructor() { - ~~~~~~~~~~~~~~~ - this.foo = "bar"; - ~~~~~~~~~~~~~~~~~~~~ - ~~~~ -!!! error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. - } - ~~~ -!!! error TS2377: Constructors for derived classes must contain a 'super' call. - _render(error) { - ~~~~~ !!! error TS7006: Parameter 'error' implicitly has an 'any' type. - const message = error.message || DEFAULT_MESSAGE; - ~~~~~~~~~~~~~~~ -!!! error TS2663: Cannot find name 'DEFAULT_MESSAGE'. Did you mean the instance member 'this.DEFAULT_MESSAGE'? - } - } + const message = error.message || DEFAULT_MESSAGE; + } + } }); \ No newline at end of file diff --git a/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts index 51af2b276a2..58844d98fd8 100644 --- a/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts +++ b/tests/cases/compiler/checkIndexConstraintOfJavascriptClassExpression.ts @@ -5,14 +5,15 @@ // @noEmit: true // @out: foo.js someFunction(function(BaseClass) { - 'use strict'; - class Hello extends BaseClass { - const DEFAULT_MESSAGE = "nop!"; - constructor() { - this.foo = "bar"; - } - _render(error) { - const message = error.message || DEFAULT_MESSAGE; - } - } + 'use strict'; + const DEFAULT_MESSAGE = "nop!"; + class Hello extends BaseClass { + constructor() { + super(); + this.foo = "bar"; + } + _render(error) { + const message = error.message || DEFAULT_MESSAGE; + } + } }); From b00aea5c7cb5ada80bce995a34bc83eb394e1dad Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 8 May 2017 11:45:02 -0700 Subject: [PATCH 118/282] Parameter improvements --- src/compiler/checker.ts | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8a84fe42515..1fae8206f49 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2812,16 +2812,26 @@ namespace ts { const parameterType = getTypeOfSymbol(parameterSymbol); const parameterTypeNode = typeToTypeNodeHelper(parameterType, context); const name = getDeepSynthesizedClone(parameterDeclaration.name); + + let questionToken: Token | undefined; + let initializer: Expression | undefined; + if (isOptionalParameter(parameterDeclaration)) { + questionToken = createToken(SyntaxKind.QuestionToken); + } + else { // TODO(aozgaa): In the future, check initializer accessibility. + initializer = parameterDeclaration.initializer; + } const parameterNode = createParameter( parameterDeclaration.decorators, parameterDeclaration.modifiers, - parameterDeclaration.dotDotDotToken && createToken(SyntaxKind.DotDotDotToken), - // Clone name to remove trivia. + (parameterDeclaration ? isRestParameter(parameterDeclaration) : isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) ? + createToken(SyntaxKind.DotDotDotToken) : + undefined, name, - parameterDeclaration.questionToken && createToken(SyntaxKind.QuestionToken), + questionToken, parameterTypeNode, - parameterDeclaration.initializer); + initializer); return parameterNode; } From 8035e999218ebd2180d59e44a64098f1af14dcd7 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 8 May 2017 12:00:52 -0700 Subject: [PATCH 119/282] Given `import *` of an `export =` module, raise an error but still return a symbol. --- src/compiler/checker.ts | 3 +- .../es6ExportEqualsInterop.errors.txt | 29 ++++++++++++++++++- .../reference/es6ExportEqualsInterop.js | 2 -- ...signatureHelpImportStarFromExportEquals.ts | 15 ++++++++++ 4 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 tests/cases/fourslash/signatureHelpImportStarFromExportEquals.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 14d80fccd26..6d131167fc2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1684,10 +1684,9 @@ namespace ts { // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol: Symbol, moduleReferenceExpression: Expression, dontResolveAlias: boolean): Symbol { - let symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable))) { error(moduleReferenceExpression, Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } diff --git a/tests/baselines/reference/es6ExportEqualsInterop.errors.txt b/tests/baselines/reference/es6ExportEqualsInterop.errors.txt index 4a9f7dcb506..4675136d081 100644 --- a/tests/baselines/reference/es6ExportEqualsInterop.errors.txt +++ b/tests/baselines/reference/es6ExportEqualsInterop.errors.txt @@ -14,11 +14,20 @@ tests/cases/compiler/main.ts(36,8): error TS1192: Module '"class-module"' has no tests/cases/compiler/main.ts(39,21): error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. tests/cases/compiler/main.ts(45,21): error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. tests/cases/compiler/main.ts(47,21): error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(50,1): error TS2693: 'y1' only refers to a type, but is being used as a value here. +tests/cases/compiler/main.ts(56,4): error TS2339: Property 'a' does not exist on type '() => any'. +tests/cases/compiler/main.ts(58,4): error TS2339: Property 'a' does not exist on type 'typeof Foo'. +tests/cases/compiler/main.ts(62,10): error TS2305: Module '"interface"' has no exported member 'a'. tests/cases/compiler/main.ts(62,25): error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(68,10): error TS2305: Module '"function"' has no exported member 'a'. tests/cases/compiler/main.ts(68,25): error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(70,10): error TS2305: Module '"class"' has no exported member 'a'. tests/cases/compiler/main.ts(70,25): error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(85,10): error TS2305: Module '"interface"' has no exported member 'a'. tests/cases/compiler/main.ts(85,25): error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(91,10): error TS2305: Module '"function"' has no exported member 'a'. tests/cases/compiler/main.ts(91,25): error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. +tests/cases/compiler/main.ts(93,10): error TS2305: Module '"class"' has no exported member 'a'. tests/cases/compiler/main.ts(93,25): error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. tests/cases/compiler/main.ts(97,15): error TS2498: Module '"interface"' uses 'export =' and cannot be used with 'export *'. tests/cases/compiler/main.ts(98,15): error TS2498: Module '"variable"' uses 'export =' and cannot be used with 'export *'. @@ -32,7 +41,7 @@ tests/cases/compiler/main.ts(105,15): error TS2498: Module '"class"' uses 'expor tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses 'export =' and cannot be used with 'export *'. -==== tests/cases/compiler/main.ts (32 errors) ==== +==== tests/cases/compiler/main.ts (41 errors) ==== /// // import-equals @@ -115,18 +124,26 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses import * as y0 from "class-module"; y1.a; + ~~ +!!! error TS2693: 'y1' only refers to a type, but is being used as a value here. y2.a; y3.a; y4.a; y5.a; y6.a; y7.a; + ~ +!!! error TS2339: Property 'a' does not exist on type '() => any'. y8.a; y9.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'typeof Foo'. y0.a; // named import import { a as a1 } from "interface"; + ~ +!!! error TS2305: Module '"interface"' has no exported member 'a'. ~~~~~~~~~~~ !!! error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. import { a as a2 } from "variable"; @@ -135,10 +152,14 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses import { a as a5 } from "interface-module"; import { a as a6 } from "variable-module"; import { a as a7 } from "function"; + ~ +!!! error TS2305: Module '"function"' has no exported member 'a'. ~~~~~~~~~~ !!! error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. import { a as a8 } from "function-module"; import { a as a9 } from "class"; + ~ +!!! error TS2305: Module '"class"' has no exported member 'a'. ~~~~~~~ !!! error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. import { a as a0 } from "class-module"; @@ -156,6 +177,8 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses // named export export { a as a1 } from "interface"; + ~ +!!! error TS2305: Module '"interface"' has no exported member 'a'. ~~~~~~~~~~~ !!! error TS2497: Module '"interface"' resolves to a non-module entity and cannot be imported using this construct. export { a as a2 } from "variable"; @@ -164,10 +187,14 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses export { a as a5 } from "interface-module"; export { a as a6 } from "variable-module"; export { a as a7 } from "function"; + ~ +!!! error TS2305: Module '"function"' has no exported member 'a'. ~~~~~~~~~~ !!! error TS2497: Module '"function"' resolves to a non-module entity and cannot be imported using this construct. export { a as a8 } from "function-module"; export { a as a9 } from "class"; + ~ +!!! error TS2305: Module '"class"' has no exported member 'a'. ~~~~~~~ !!! error TS2497: Module '"class"' resolves to a non-module entity and cannot be imported using this construct. export { a as a0 } from "class-module"; diff --git a/tests/baselines/reference/es6ExportEqualsInterop.js b/tests/baselines/reference/es6ExportEqualsInterop.js index 5e04221df8b..13908a29e2d 100644 --- a/tests/baselines/reference/es6ExportEqualsInterop.js +++ b/tests/baselines/reference/es6ExportEqualsInterop.js @@ -232,8 +232,6 @@ z7.a; z8.a; z9.a; z0.a; -// namespace import -var y1 = require("interface"); var y2 = require("variable"); var y3 = require("interface-variable"); var y4 = require("module"); diff --git a/tests/cases/fourslash/signatureHelpImportStarFromExportEquals.ts b/tests/cases/fourslash/signatureHelpImportStarFromExportEquals.ts new file mode 100644 index 00000000000..cdf4b0a5c64 --- /dev/null +++ b/tests/cases/fourslash/signatureHelpImportStarFromExportEquals.ts @@ -0,0 +1,15 @@ +/// + +// @allowJs: true + +// @Filename: /node_modules/@types/abs/index.d.ts +////declare function abs(str: string): string; +////export = abs; + +// @Filename: /a.js +////import * as abs from "abs"; +////abs/**/; + +goTo.marker(); +edit.insert('('); +verify.currentSignatureHelpIs('abs(str: string): string'); From eb9d4c0586db80a6b773cba02d8fb24290008142 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 8 May 2017 13:25:12 -0700 Subject: [PATCH 120/282] findAllReferences: Given a synthetic property, find references for the original property. --- src/services/findAllReferences.ts | 5 ++++- tests/cases/fourslash/findAllRefsMappedType.ts | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/findAllRefsMappedType.ts diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index fd717fc546e..8dbbe3b1547 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -273,7 +273,7 @@ namespace ts.FindAllReferences.Core { } } - const symbol = checker.getSymbolAtLocation(node); + let symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -285,6 +285,9 @@ namespace ts.FindAllReferences.Core { return undefined; } + // If this property is derived from another one, find references on the original property instead. + symbol = (symbol as ts.SymbolLinks).syntheticOrigin || symbol; + // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol.declarations || !symbol.declarations.length) { return undefined; diff --git a/tests/cases/fourslash/findAllRefsMappedType.ts b/tests/cases/fourslash/findAllRefsMappedType.ts new file mode 100644 index 00000000000..97658da08c1 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsMappedType.ts @@ -0,0 +1,10 @@ +/// + +////interface T { [|{| "isWriteAccess": true, "isDefinition": true |}a|]: number; } +////type U = { readonly [K in keyof T]?: string }; +////declare const t: T; +////t.[|a|]; +////declare const u: U; +////u.[|a|]; + +verify.singleReferenceGroup("(property) T.a: number"); From bb1125a2b6fbd3ffeb9025e83b4c1a8a7032b68b Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Mon, 8 May 2017 13:31:44 -0700 Subject: [PATCH 121/282] Do not error when spread generic type --- src/compiler/checker.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2b24c947f90..e544b9239f6 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13285,11 +13285,7 @@ namespace ts { attributesArray = []; attributesTable = createMap(); } - const exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); - hasSpreadAnyType = true; - } + const exprType = getApparentType(checkExpression(attributeDecl.expression)) if (isTypeAny(exprType)) { hasSpreadAnyType = true; } From d17450bbbd81b528eabe0326a780c8b044282b3b Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Mon, 8 May 2017 13:35:09 -0700 Subject: [PATCH 122/282] Update tests and baselines --- .../tsxAttributeResolution5.errors.txt | 19 ++- ...ionComponentsWithTypeArguments2.errors.txt | 20 ++- ...ionComponentsWithTypeArguments3.errors.txt | 50 ------ ...nctionComponentsWithTypeArguments3.symbols | 159 +++++++++--------- ...FunctionComponentsWithTypeArguments3.types | 5 +- ...ionComponentsWithTypeArguments4.errors.txt | 10 +- ...ionComponentsWithTypeArguments5.errors.txt | 25 +-- ...essFunctionComponentsWithTypeArguments5.js | 9 +- ...ssFunctionComponentsWithTypeArguments5.tsx | 3 +- 9 files changed, 125 insertions(+), 175 deletions(-) delete mode 100644 tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.errors.txt diff --git a/tests/baselines/reference/tsxAttributeResolution5.errors.txt b/tests/baselines/reference/tsxAttributeResolution5.errors.txt index ffbd41a07b2..0c6be5f35d0 100644 --- a/tests/baselines/reference/tsxAttributeResolution5.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution5.errors.txt @@ -1,11 +1,13 @@ -tests/cases/conformance/jsx/file.tsx(17,16): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(21,16): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(25,16): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(21,16): error TS2322: Type '{ x: number; }' is not assignable to type 'Attribs1'. + Types of property 'x' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(25,16): error TS2322: Type '{ y: string; }' is not assignable to type 'Attribs1'. + Property 'x' is missing in type '{ y: string; }'. tests/cases/conformance/jsx/file.tsx(29,8): error TS2322: Type '{}' is not assignable to type 'Attribs1'. Property 'x' is missing in type '{}'. -==== tests/cases/conformance/jsx/file.tsx (4 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== declare module JSX { interface Element { } interface IntrinsicElements { @@ -23,20 +25,21 @@ tests/cases/conformance/jsx/file.tsx(29,8): error TS2322: Type '{}' is not assig function make1 (obj: T) { return ; // OK - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. } function make2 (obj: T) { return ; // Error (x is number, not string) ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. +!!! error TS2322: Type '{ x: number; }' is not assignable to type 'Attribs1'. +!!! error TS2322: Types of property 'x' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. } function make3 (obj: T) { return ; // Error, missing x ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. +!!! error TS2322: Type '{ y: string; }' is not assignable to type 'Attribs1'. +!!! error TS2322: Property 'x' is missing in type '{ y: string; }'. } diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt index c98c918f3c5..c8ff457711c 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt @@ -1,5 +1,10 @@ -tests/cases/conformance/jsx/file.tsx(8,34): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(13,34): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(8,34): error TS2322: Type '{ ignore-prop: 10; prop: number; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. + Type '{ ignore-prop: 10; prop: number; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. + Types of property '"ignore-prop"' are incompatible. + Type '10' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(13,34): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. + Type '{}' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. + Property 'prop' is missing in type '{}'. tests/cases/conformance/jsx/file.tsx(20,19): error TS2322: Type '{ func: (a: number, b: string) => void; }' is not assignable to type 'IntrinsicAttributes & { func: (arg: number) => void; }'. Type '{ func: (a: number, b: string) => void; }' is not assignable to type '{ func: (arg: number) => void; }'. Types of property 'func' are incompatible. @@ -19,15 +24,20 @@ tests/cases/conformance/jsx/file.tsx(31,10): error TS2453: The type argument for // Error function Bar(arg: T) { let a1 = ; - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. + ~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ ignore-prop: 10; prop: number; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. +!!! error TS2322: Type '{ ignore-prop: 10; prop: number; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. +!!! error TS2322: Types of property '"ignore-prop"' are incompatible. +!!! error TS2322: Type '10' is not assignable to type 'string'. } // Error function Baz(arg: T) { let a0 = ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. +!!! error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. +!!! error TS2322: Type '{}' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. +!!! error TS2322: Property 'prop' is missing in type '{}'. } declare function Link(l: {func: (arg: U)=>void}): JSX.Element; diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.errors.txt deleted file mode 100644 index fdf65ca1746..00000000000 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.errors.txt +++ /dev/null @@ -1,50 +0,0 @@ -tests/cases/conformance/jsx/file.tsx(9,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(10,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(11,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(12,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(14,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(14,63): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(15,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(15,55): error TS2698: Spread types may only be created from object types. - - -==== tests/cases/conformance/jsx/file.tsx (8 errors) ==== - import React = require('react') - - declare function OverloadComponent(): JSX.Element; - declare function OverloadComponent(attr: {b: U, a?: string, "ignore-prop": boolean}): JSX.Element; - declare function OverloadComponent(attr: {b: U, a: T}): JSX.Element; - - // OK - function Baz(arg1: T, arg2: U) { - let a0 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a1 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a2 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a3 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a4 = ; - let a5 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - let a6 = ; - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. - } - - declare function Link(l: {func: (arg: U)=>void}): JSX.Element; - declare function Link(l: {func: (arg1:U, arg2: string)=>void}): JSX.Element; - function createLink(func: (a: number)=>void) { - let o = - let o1 = {}} />; - } \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols index ebd80b3d262..e93eb374aa7 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.symbols @@ -1,128 +1,127 @@ === tests/cases/conformance/jsx/file.tsx === - import React = require('react') >React : Symbol(React, Decl(file.tsx, 0, 0)) declare function OverloadComponent(): JSX.Element; ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->U : Symbol(U, Decl(file.tsx, 3, 35)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>U : Symbol(U, Decl(file.tsx, 2, 35)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) declare function OverloadComponent(attr: {b: U, a?: string, "ignore-prop": boolean}): JSX.Element; ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->U : Symbol(U, Decl(file.tsx, 4, 35)) ->attr : Symbol(attr, Decl(file.tsx, 4, 38)) ->b : Symbol(b, Decl(file.tsx, 4, 45)) ->U : Symbol(U, Decl(file.tsx, 4, 35)) ->a : Symbol(a, Decl(file.tsx, 4, 50)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>U : Symbol(U, Decl(file.tsx, 3, 35)) +>attr : Symbol(attr, Decl(file.tsx, 3, 38)) +>b : Symbol(b, Decl(file.tsx, 3, 45)) +>U : Symbol(U, Decl(file.tsx, 3, 35)) +>a : Symbol(a, Decl(file.tsx, 3, 50)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) declare function OverloadComponent(attr: {b: U, a: T}): JSX.Element; ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->T : Symbol(T, Decl(file.tsx, 5, 35)) ->U : Symbol(U, Decl(file.tsx, 5, 37)) ->attr : Symbol(attr, Decl(file.tsx, 5, 41)) ->b : Symbol(b, Decl(file.tsx, 5, 48)) ->U : Symbol(U, Decl(file.tsx, 5, 37)) ->a : Symbol(a, Decl(file.tsx, 5, 53)) ->T : Symbol(T, Decl(file.tsx, 5, 35)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>T : Symbol(T, Decl(file.tsx, 4, 35)) +>U : Symbol(U, Decl(file.tsx, 4, 37)) +>attr : Symbol(attr, Decl(file.tsx, 4, 41)) +>b : Symbol(b, Decl(file.tsx, 4, 48)) +>U : Symbol(U, Decl(file.tsx, 4, 37)) +>a : Symbol(a, Decl(file.tsx, 4, 53)) +>T : Symbol(T, Decl(file.tsx, 4, 35)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) // OK function Baz(arg1: T, arg2: U) { ->Baz : Symbol(Baz, Decl(file.tsx, 5, 74)) ->T : Symbol(T, Decl(file.tsx, 8, 13)) ->b : Symbol(b, Decl(file.tsx, 8, 24)) ->U : Symbol(U, Decl(file.tsx, 8, 35)) ->a : Symbol(a, Decl(file.tsx, 8, 47)) ->b : Symbol(b, Decl(file.tsx, 8, 58)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) ->T : Symbol(T, Decl(file.tsx, 8, 13)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->U : Symbol(U, Decl(file.tsx, 8, 35)) +>Baz : Symbol(Baz, Decl(file.tsx, 4, 74)) +>T : Symbol(T, Decl(file.tsx, 7, 13)) +>b : Symbol(b, Decl(file.tsx, 7, 24)) +>U : Symbol(U, Decl(file.tsx, 7, 35)) +>a : Symbol(a, Decl(file.tsx, 7, 47)) +>b : Symbol(b, Decl(file.tsx, 7, 58)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) +>T : Symbol(T, Decl(file.tsx, 7, 13)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>U : Symbol(U, Decl(file.tsx, 7, 35)) let a0 = ; ->a0 : Symbol(a0, Decl(file.tsx, 9, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) ->a : Symbol(a, Decl(file.tsx, 9, 41)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 9, 51)) +>a0 : Symbol(a0, Decl(file.tsx, 8, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) +>a : Symbol(a, Decl(file.tsx, 8, 41)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 8, 51)) let a1 = ; ->a1 : Symbol(a1, Decl(file.tsx, 10, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->ignore-pro : Symbol(ignore-pro, Decl(file.tsx, 10, 41)) +>a1 : Symbol(a1, Decl(file.tsx, 9, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>ignore-pro : Symbol(ignore-pro, Decl(file.tsx, 9, 41)) let a2 = ; ->a2 : Symbol(a2, Decl(file.tsx, 11, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) +>a2 : Symbol(a2, Decl(file.tsx, 10, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) let a3 = ; ->a3 : Symbol(a3, Decl(file.tsx, 12, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 12, 41)) +>a3 : Symbol(a3, Decl(file.tsx, 11, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 11, 41)) let a4 = ; ->a4 : Symbol(a4, Decl(file.tsx, 13, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) +>a4 : Symbol(a4, Decl(file.tsx, 12, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) let a5 = ; ->a5 : Symbol(a5, Decl(file.tsx, 14, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 14, 41)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) +>a5 : Symbol(a5, Decl(file.tsx, 13, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 13, 41)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) let a6 = ; ->a6 : Symbol(a6, Decl(file.tsx, 15, 7)) ->OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 1, 31), Decl(file.tsx, 3, 53), Decl(file.tsx, 4, 101)) ->arg2 : Symbol(arg2, Decl(file.tsx, 8, 78)) ->ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 15, 41)) ->arg1 : Symbol(arg1, Decl(file.tsx, 8, 70)) +>a6 : Symbol(a6, Decl(file.tsx, 14, 7)) +>OverloadComponent : Symbol(OverloadComponent, Decl(file.tsx, 0, 31), Decl(file.tsx, 2, 53), Decl(file.tsx, 3, 101)) +>arg2 : Symbol(arg2, Decl(file.tsx, 7, 78)) +>ignore-prop : Symbol(ignore-prop, Decl(file.tsx, 14, 41)) +>arg1 : Symbol(arg1, Decl(file.tsx, 7, 70)) } declare function Link(l: {func: (arg: U)=>void}): JSX.Element; ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->U : Symbol(U, Decl(file.tsx, 18, 22)) ->l : Symbol(l, Decl(file.tsx, 18, 25)) ->func : Symbol(func, Decl(file.tsx, 18, 29)) ->arg : Symbol(arg, Decl(file.tsx, 18, 36)) ->U : Symbol(U, Decl(file.tsx, 18, 22)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>U : Symbol(U, Decl(file.tsx, 17, 22)) +>l : Symbol(l, Decl(file.tsx, 17, 25)) +>func : Symbol(func, Decl(file.tsx, 17, 29)) +>arg : Symbol(arg, Decl(file.tsx, 17, 36)) +>U : Symbol(U, Decl(file.tsx, 17, 22)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) declare function Link(l: {func: (arg1:U, arg2: string)=>void}): JSX.Element; ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->U : Symbol(U, Decl(file.tsx, 19, 22)) ->l : Symbol(l, Decl(file.tsx, 19, 25)) ->func : Symbol(func, Decl(file.tsx, 19, 29)) ->arg1 : Symbol(arg1, Decl(file.tsx, 19, 36)) ->U : Symbol(U, Decl(file.tsx, 19, 22)) ->arg2 : Symbol(arg2, Decl(file.tsx, 19, 43)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>U : Symbol(U, Decl(file.tsx, 18, 22)) +>l : Symbol(l, Decl(file.tsx, 18, 25)) +>func : Symbol(func, Decl(file.tsx, 18, 29)) +>arg1 : Symbol(arg1, Decl(file.tsx, 18, 36)) +>U : Symbol(U, Decl(file.tsx, 18, 22)) +>arg2 : Symbol(arg2, Decl(file.tsx, 18, 43)) >JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) >Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) function createLink(func: (a: number)=>void) { ->createLink : Symbol(createLink, Decl(file.tsx, 19, 79)) ->func : Symbol(func, Decl(file.tsx, 20, 20)) ->a : Symbol(a, Decl(file.tsx, 20, 27)) +>createLink : Symbol(createLink, Decl(file.tsx, 18, 79)) +>func : Symbol(func, Decl(file.tsx, 19, 20)) +>a : Symbol(a, Decl(file.tsx, 19, 27)) let o = ->o : Symbol(o, Decl(file.tsx, 21, 7)) ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->func : Symbol(func, Decl(file.tsx, 21, 17)) ->func : Symbol(func, Decl(file.tsx, 20, 20)) +>o : Symbol(o, Decl(file.tsx, 20, 7)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>func : Symbol(func, Decl(file.tsx, 20, 17)) +>func : Symbol(func, Decl(file.tsx, 19, 20)) let o1 = {}} />; ->o1 : Symbol(o1, Decl(file.tsx, 22, 7)) ->Link : Symbol(Link, Decl(file.tsx, 16, 1), Decl(file.tsx, 18, 65)) ->func : Symbol(func, Decl(file.tsx, 22, 18)) ->a : Symbol(a, Decl(file.tsx, 22, 26)) ->b : Symbol(b, Decl(file.tsx, 22, 35)) +>o1 : Symbol(o1, Decl(file.tsx, 21, 7)) +>Link : Symbol(Link, Decl(file.tsx, 15, 1), Decl(file.tsx, 17, 65)) +>func : Symbol(func, Decl(file.tsx, 21, 18)) +>a : Symbol(a, Decl(file.tsx, 21, 26)) +>b : Symbol(b, Decl(file.tsx, 21, 35)) } diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types index f85638d0edd..aa38d2ccf8a 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments3.types @@ -1,5 +1,4 @@ === tests/cases/conformance/jsx/file.tsx === - import React = require('react') >React : typeof React @@ -131,8 +130,8 @@ function createLink(func: (a: number)=>void) { >o1 : JSX.Element >{}} /> : JSX.Element >Link : { (l: { func: (arg: U) => void; }): JSX.Element; (l: { func: (arg1: U, arg2: string) => void; }): JSX.Element; } ->func : (a: number, b: string) => void ->(a:number, b:string)=>{} : (a: number, b: string) => void +>func : (a: number, b: string) => any +>(a:number, b:string)=>{} : (a: number, b: string) => any >a : number >b : string } diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt index 7988bbdf414..d9b50ef31c6 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt @@ -1,7 +1,9 @@ tests/cases/conformance/jsx/file.tsx(9,33): error TS2322: Type '{ a: number; }' is not assignable to type 'IntrinsicAttributes & { b: {}; a: number; }'. Type '{ a: number; }' is not assignable to type '{ b: {}; a: number; }'. Property 'b' is missing in type '{ a: number; }'. -tests/cases/conformance/jsx/file.tsx(10,33): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(10,33): error TS2322: Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. + Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. + Property 'a' is missing in type '{ b: number; }'. ==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== @@ -19,6 +21,8 @@ tests/cases/conformance/jsx/file.tsx(10,33): error TS2698: Spread types may only !!! error TS2322: Type '{ a: number; }' is not assignable to type '{ b: {}; a: number; }'. !!! error TS2322: Property 'b' is missing in type '{ a: number; }'. let a2 = // missing a - ~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. +!!! error TS2322: Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. +!!! error TS2322: Property 'a' is missing in type '{ b: number; }'. } \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt index 314f8b6cdad..3f5623921fd 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt @@ -1,37 +1,24 @@ -tests/cases/conformance/jsx/file.tsx(6,25): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(7,25): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(15,33): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(16,34): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/jsx/file.tsx(17,33): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/jsx/file.tsx(16,42): error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & { prop: number; }'. -==== tests/cases/conformance/jsx/file.tsx (5 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== import React = require('react') - // Error, can only spread object type declare function Component(l: U): JSX.Element; function createComponent(arg: T) { - let a1 = ; - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. + // let a1 = ; let a2 = ; - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. } declare function ComponentSpecific(l: { prop: U }): JSX.Element; declare function ComponentSpecific1(l: { prop: U, "ignore-prop": number }): JSX.Element; - // Error, can only spread object type function Bar(arg: T) { let a1 = ; // U is number - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. let a2 = ; // U is number - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. let a3 = ; // U is "hello" - ~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. + let a4 = ; // U is "hello" + ~~~~~~~~~~~~~ +!!! error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & { prop: number; }'. } \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js index b5e215dada3..e77e79ee732 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js @@ -1,21 +1,20 @@ //// [file.tsx] import React = require('react') -// Error, can only spread object type declare function Component(l: U): JSX.Element; function createComponent(arg: T) { - let a1 = ; + // let a1 = ; let a2 = ; } declare function ComponentSpecific(l: { prop: U }): JSX.Element; declare function ComponentSpecific1(l: { prop: U, "ignore-prop": number }): JSX.Element; -// Error, can only spread object type function Bar(arg: T) { let a1 = ; // U is number let a2 = ; // U is number let a3 = ; // U is "hello" + let a4 = ; // U is "hello" } @@ -24,13 +23,13 @@ define(["require", "exports", "react"], function (require, exports, React) { "use strict"; exports.__esModule = true; function createComponent(arg) { - var a1 = ; + // let a1 = ; var a2 = ; } - // Error, can only spread object type function Bar(arg) { var a1 = ; // U is number var a2 = ; // U is number var a3 = ; // U is "hello" + var a4 = ; // U is "hello" } }); diff --git a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx index 527eb689ddb..c19bfdf43bd 100644 --- a/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx +++ b/tests/cases/conformance/jsx/tsxStatelessFunctionComponentsWithTypeArguments5.tsx @@ -6,7 +6,6 @@ import React = require('react') -// Error, can only spread object type declare function Component(l: U): JSX.Element; function createComponent(arg: T) { let a1 = ; @@ -16,9 +15,9 @@ function createComponent(arg: T) { declare function ComponentSpecific(l: { prop: U }): JSX.Element; declare function ComponentSpecific1(l: { prop: U, "ignore-prop": number }): JSX.Element; -// Error, can only spread object type function Bar(arg: T) { let a1 = ; // U is number let a2 = ; // U is number let a3 = ; // U is "hello" + let a4 = ; // U is "hello" } From 73a944711f01be6a8dd8af140122d26ac5427751 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 8 May 2017 13:49:53 -0700 Subject: [PATCH 123/282] Remove checks for `symbol.declarations` --- src/services/findAllReferences.ts | 14 +------------- tests/cases/fourslash/findAllRefsMappedType.ts | 7 ++++++- 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 8dbbe3b1547..40572b11d34 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -108,10 +108,6 @@ namespace ts.FindAllReferences { switch (def.type) { case "symbol": { const { symbol, node } = def; - const declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } const { displayParts, kind } = getDefinitionKindAndDisplayParts(symbol, node, checker); const name = displayParts.map(p => p.text).join(""); return { node, name, kind, displayParts }; @@ -273,7 +269,7 @@ namespace ts.FindAllReferences.Core { } } - let symbol = checker.getSymbolAtLocation(node); + const symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -285,14 +281,6 @@ namespace ts.FindAllReferences.Core { return undefined; } - // If this property is derived from another one, find references on the original property instead. - symbol = (symbol as ts.SymbolLinks).syntheticOrigin || symbol; - - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; - } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } diff --git a/tests/cases/fourslash/findAllRefsMappedType.ts b/tests/cases/fourslash/findAllRefsMappedType.ts index 97658da08c1..7daf0296d94 100644 --- a/tests/cases/fourslash/findAllRefsMappedType.ts +++ b/tests/cases/fourslash/findAllRefsMappedType.ts @@ -7,4 +7,9 @@ ////declare const u: U; ////u.[|a|]; -verify.singleReferenceGroup("(property) T.a: number"); +const ranges = test.ranges(); +const [r0, r1, r2] = ranges; +verify.referenceGroups([r0, r1], [{ definition: "(property) T.a: number", ranges }]); +verify.referenceGroups(r2, [ + { definition: "(property) T.a: number", ranges: [r0, r1] }, + { definition: "(property) a: string", ranges: [r2] }]); From dd94ad239abaafb9a4524bb8a437d55189b3807f Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 8 May 2017 14:16:53 -0700 Subject: [PATCH 124/282] Revert "Turn ClassElement and TypeElement into unions too" This reverts commit 22f353ac940bfd4e170d9e56a094fdd385476191. --- src/compiler/types.ts | 75 +++++++++++++++++++++++-------------------- 1 file changed, 41 insertions(+), 34 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4ec5c0f97bf..043c8b9a0b1 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -616,6 +616,7 @@ namespace ts { | CallExpression | CallSignatureDeclaration | ClassDeclaration + | ClassElement | ClassExpression | ClassLikeDeclaration | ConstructSignatureDeclaration @@ -716,14 +717,13 @@ namespace ts { typeParameters?: NodeArray; parameters: NodeArray; type?: TypeNode; - questionToken?: QuestionToken; } - export interface CallSignatureDeclaration extends SignatureDeclaration { + export interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { kind: SyntaxKind.CallSignature; } - export interface ConstructSignatureDeclaration extends SignatureDeclaration { + export interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { kind: SyntaxKind.ConstructSignature; } @@ -762,7 +762,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface PropertySignature extends DeclarationBase { + export interface PropertySignature extends TypeElement { kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; // Declared property name questionToken?: QuestionToken; // Present on optional property @@ -770,7 +770,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface PropertyDeclaration extends DeclarationBase { + export interface PropertyDeclaration extends ClassElement { kind: SyntaxKind.PropertyDeclaration; questionToken?: QuestionToken; // Present for use with reporting a grammar error name: PropertyName; @@ -876,7 +876,7 @@ namespace ts { body?: FunctionBody; } - export interface MethodSignature extends SignatureDeclaration { + export interface MethodSignature extends SignatureDeclaration, TypeElement { kind: SyntaxKind.MethodSignature; name: PropertyName; } @@ -890,28 +890,27 @@ namespace ts { // Because of this, it may be necessary to determine what sort of MethodDeclaration you have // at later stages of the compiler pipeline. In that case, you can either check the parent kind // of the method, or use helpers like isObjectLiteralMethodDeclaration - export interface MethodDeclaration extends FunctionLikeDeclaration, ObjectLiteralElement { + export interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - export interface ConstructorDeclaration extends FunctionLikeDeclaration { + export interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ - export interface SemicolonClassElement extends DeclarationBase { + export interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; - name?: PropertyName; } // See the comment on MethodDeclaration for the intuition behind GetAccessorDeclaration being a // ClassElement and an ObjectLiteralElement. - export interface GetAccessorDeclaration extends FunctionLikeDeclaration, ObjectLiteralElement { + export interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; @@ -920,7 +919,7 @@ namespace ts { // See the comment on MethodDeclaration for the intuition behind SetAccessorDeclaration being a // ClassElement and an ObjectLiteralElement. - export interface SetAccessorDeclaration extends FunctionLikeDeclaration, ObjectLiteralElement { + export interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; @@ -929,7 +928,7 @@ namespace ts { export type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; - export interface IndexSignatureDeclaration extends SignatureDeclaration { + export interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; } @@ -1696,7 +1695,7 @@ namespace ts { kind: SyntaxKind.DebuggerStatement; } - export interface MissingDeclaration extends DeclarationStatement, ObjectLiteralElement { + export interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { kind: SyntaxKind.MissingDeclaration; name?: Identifier; } @@ -1864,26 +1863,34 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export type ClassElement = - | PropertyDeclaration - | MethodDeclaration - | ConstructorDeclaration - | SemicolonClassElement - | GetAccessorDeclaration - | SetAccessorDeclaration - | IndexSignatureDeclaration - | MissingDeclaration; + export interface ClassElement extends DeclarationBase { + kind: + | SyntaxKind.PropertyDeclaration + | SyntaxKind.MethodDeclaration + | SyntaxKind.Constructor + | SyntaxKind.SemicolonClassElement + | SyntaxKind.GetAccessor + | SyntaxKind.SetAccessor + | SyntaxKind.IndexSignature + | SyntaxKind.MissingDeclaration; + _classElementBrand: any; + name?: PropertyName; + } - export type TypeElement = - | CallSignatureDeclaration - | ConstructSignatureDeclaration - | PropertySignature - | MethodSignature - | IndexSignatureDeclaration - | MissingDeclaration - | IndexSignatureDeclaration - | JSDocPropertyTag - | JSDocRecordMember; + export interface TypeElement extends DeclarationBase { + kind: + | SyntaxKind.CallSignature + | SyntaxKind.ConstructSignature + | SyntaxKind.PropertySignature + | SyntaxKind.MethodSignature + | SyntaxKind.IndexSignature + | SyntaxKind.MissingDeclaration + | SyntaxKind.JSDocPropertyTag + | SyntaxKind.JSDocRecordMember; + _typeElementBrand: any; + name?: PropertyName; + questionToken?: QuestionToken; + } export interface InterfaceDeclaration extends DeclarationStatement { kind: SyntaxKind.InterfaceDeclaration; @@ -2217,7 +2224,7 @@ namespace ts { jsDocTypeLiteral?: JSDocTypeLiteral; } - export interface JSDocPropertyTag extends JSDocTag { + export interface JSDocPropertyTag extends JSDocTag, TypeElement { kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; From e81733b82723dac1f853edec8ea8d8c4c6fc48a5 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 8 May 2017 14:17:11 -0700 Subject: [PATCH 125/282] Revert "Fix lint" This reverts commit b39c319f0c4ee9b460ed51eba77e8c0958896c80. --- src/compiler/types.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 043c8b9a0b1..de71fbfdabe 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -711,7 +711,7 @@ namespace ts { | SyntaxKind.SetAccessor | SyntaxKind.Constructor | SyntaxKind.ArrowFunction - | SyntaxKind.FunctionExpression; + | SyntaxKind.FunctionExpression name?: PropertyName; typeParameters?: NodeArray; @@ -814,8 +814,9 @@ namespace ts { } /** - * There aren't any explicit subtypes of VariableLikeDeclaration, + * There aren't any explicit subtypes of VariableLikeDeclaration; * it's just structurally relatable to a number of types. + * (Maybe it should be an intersection of the below types.) */ export interface VariableLikeDeclaration extends DeclarationBase { kind: From acec74b1afc93bba32ac44afc0c6aa8fc12e2807 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 8 May 2017 14:24:45 -0700 Subject: [PATCH 126/282] Revert "Convert `Declaration` to union, not type hierarchy" This reverts commit 573040f0cfa713929bfa1fe84f4fd2a81cc82658. --- src/compiler/binder.ts | 6 +- src/compiler/checker.ts | 20 +-- src/compiler/transformers/es2015.ts | 2 +- src/compiler/types.ts | 182 ++++++---------------------- src/compiler/utilities.ts | 9 +- 5 files changed, 58 insertions(+), 161 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 8506378e216..38cb93bff7e 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -304,7 +304,7 @@ namespace ts { } function getDisplayName(node: Declaration): string { - return (node as DeclarationBase).name ? declarationNameToString((node as DeclarationBase).name) : getDeclarationName(node); + return (node as RealDeclaration).name ? declarationNameToString((node as RealDeclaration).name) : getDeclarationName(node); } /** @@ -367,8 +367,8 @@ namespace ts { symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } else { - if ((node as DeclarationBase).name) { - (node as DeclarationBase).name.parent = node; + if ((node as RealDeclaration).name) { + (node as RealDeclaration).name.parent = node; } // Report errors every position with duplicate declaration diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index aea175ac8b1..f7d7a79f9a0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3621,7 +3621,7 @@ namespace ts { }); } - function isDeclarationVisible(node: Node): boolean { + function isDeclarationVisible(node: Declaration): boolean { if (node) { const links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -3635,10 +3635,10 @@ namespace ts { function determineIfDeclarationIsVisible() { switch (node.kind) { case SyntaxKind.BindingElement: - return isDeclarationVisible(node.parent.parent); + return isDeclarationVisible(node.parent.parent); case SyntaxKind.VariableDeclaration: - const declaration = node as VariableDeclaration; - if (isBindingPattern(declaration.name) && !declaration.name.elements.length) { + if (isBindingPattern(node.name) && + !(node.name).elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } @@ -3661,7 +3661,7 @@ namespace ts { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent); + return isDeclarationVisible(parent); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: @@ -3691,7 +3691,7 @@ namespace ts { case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: case SyntaxKind.ParenthesizedType: - return isDeclarationVisible(node.parent); + return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible @@ -6236,8 +6236,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return (node).name.kind === SyntaxKind.ComputedPropertyName - && traverse((node).name); + return (node).name.kind === SyntaxKind.ComputedPropertyName + && traverse((node).name); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && forEachChild(node, traverse); @@ -21909,7 +21909,7 @@ namespace ts { function isTypeDeclarationName(name: Node): boolean { return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && - (name.parent).name === name; + (name.parent).name === name; } function isTypeDeclaration(node: Node): boolean { @@ -22537,7 +22537,7 @@ namespace ts { // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node: Node): boolean { + function isDeclarationWithCollidingName(node: Declaration): boolean { node = getParseTreeNode(node, isDeclaration); if (node) { const symbol = getSymbolOfNode(node); diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 4165b0679e1..188da04b36c 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -3748,7 +3748,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.VariableDeclaration: - return (parent).name === node + return (parent).name === node && resolver.isDeclarationWithCollidingName(parent); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index de71fbfdabe..51e9d6717ee 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -603,75 +603,15 @@ namespace ts { export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; - export interface DeclarationBase extends Node { + export interface RealDeclaration extends Node { _declarationBrand: any; name?: DeclarationName; } - export type Declaration = - | ArrowFunction - // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files - | BinaryExpression - | BindingElement - | CallExpression - | CallSignatureDeclaration - | ClassDeclaration - | ClassElement - | ClassExpression - | ClassLikeDeclaration - | ConstructSignatureDeclaration - | ConstructorDeclaration - | ConstructorTypeNode - | EnumDeclaration - | EnumMember - | ExportAssignment - | ExportDeclaration - | ExportSpecifier - | FunctionDeclaration - | FunctionExpression - | FunctionTypeNode - | GetAccessorDeclaration - | ImportClause - | ImportEqualsDeclaration - | ImportSpecifier - | IndexSignatureDeclaration - | InterfaceDeclaration - | JSDocFunctionType - | JSDocNamespaceDeclaration - | JSDocPropertyTag - | JSDocTypedefTag - | JsxAttribute - | JsxAttributes - | JsxSpreadAttribute - | MappedTypeNode - | MethodDeclaration - | MethodSignature - | MissingDeclaration - | ModuleDeclaration - | NamespaceDeclaration - | NamespaceExportDeclaration - | NamespaceImport - | NewExpression - | ObjectLiteralExpression - | ParameterDeclaration - | PropertyAccessExpression - | PropertyAssignment - | PropertyDeclaration - | PropertySignature - | SemicolonClassElement - | SetAccessorDeclaration - | ShorthandPropertyAssignment - | SignatureDeclaration - | SourceFile - | SpreadAssignment - | TypeAliasDeclaration - | TypeElement - | TypeLiteralNode - | TypeParameterDeclaration - | VariableDeclaration - | VariableLikeDeclaration; + // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files + export type Declaration = RealDeclaration | BinaryExpression; - export interface DeclarationStatement extends DeclarationBase, Statement { + export interface DeclarationStatement extends RealDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } @@ -685,7 +625,7 @@ namespace ts { expression: LeftHandSideExpression; } - export interface TypeParameterDeclaration extends DeclarationBase { + export interface TypeParameterDeclaration extends RealDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -696,23 +636,7 @@ namespace ts { expression?: Expression; } - export interface SignatureDeclaration extends DeclarationBase { - kind: - | SyntaxKind.CallSignature - | SyntaxKind.ConstructSignature - | SyntaxKind.ConstructorType - | SyntaxKind.MethodSignature - | SyntaxKind.IndexSignature - | SyntaxKind.FunctionType - | SyntaxKind.JSDocFunctionType - | SyntaxKind.FunctionDeclaration - | SyntaxKind.MethodDeclaration - | SyntaxKind.GetAccessor - | SyntaxKind.SetAccessor - | SyntaxKind.Constructor - | SyntaxKind.ArrowFunction - | SyntaxKind.FunctionExpression - + export interface SignatureDeclaration extends RealDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -729,7 +653,7 @@ namespace ts { export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends DeclarationBase { + export interface VariableDeclaration extends RealDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; // Declared variable name @@ -743,7 +667,7 @@ namespace ts { declarations: NodeArray; } - export interface ParameterDeclaration extends DeclarationBase { + export interface ParameterDeclaration extends RealDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; // Present on rest parameter @@ -753,7 +677,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface BindingElement extends DeclarationBase { + export interface BindingElement extends RealDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; // Binding property name (in object binding pattern) @@ -778,7 +702,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface ObjectLiteralElement extends DeclarationBase { + export interface ObjectLiteralElement extends RealDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -813,24 +737,16 @@ namespace ts { expression: Expression; } - /** - * There aren't any explicit subtypes of VariableLikeDeclaration; - * it's just structurally relatable to a number of types. - * (Maybe it should be an intersection of the below types.) - */ - export interface VariableLikeDeclaration extends DeclarationBase { - kind: - | SyntaxKind.VariableDeclaration - | SyntaxKind.Parameter - | SyntaxKind.BindingElement - | SyntaxKind.PropertyAssignment - | SyntaxKind.PropertyDeclaration - | SyntaxKind.PropertySignature - | SyntaxKind.JsxAttribute - | SyntaxKind.ShorthandPropertyAssignment - | SyntaxKind.EnumMember - | SyntaxKind.JSDocPropertyTag - | SyntaxKind.JSDocRecordMember; + // SyntaxKind.VariableDeclaration + // SyntaxKind.Parameter + // SyntaxKind.BindingElement + // SyntaxKind.Property + // SyntaxKind.PropertyAssignment + // SyntaxKind.JsxAttribute + // SyntaxKind.ShorthandPropertyAssignment + // SyntaxKind.EnumMember + // SyntaxKind.JSDocPropertyTag + export interface VariableLikeDeclaration extends RealDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -839,6 +755,10 @@ namespace ts { initializer?: Expression; } + export interface PropertyLikeDeclaration extends RealDeclaration { + name: PropertyName; + } + export interface ObjectBindingPattern extends Node { kind: SyntaxKind.ObjectBindingPattern; parent?: VariableDeclaration | ParameterDeclaration | BindingElement; @@ -984,7 +904,7 @@ namespace ts { } // A TypeLiteral is the declaration node for an anonymous symbol. - export interface TypeLiteralNode extends TypeNode, DeclarationBase { + export interface TypeLiteralNode extends TypeNode, RealDeclaration { kind: SyntaxKind.TypeLiteral; members: NodeArray; } @@ -1028,7 +948,7 @@ namespace ts { indexType: TypeNode; } - export interface MappedTypeNode extends TypeNode, DeclarationBase { + export interface MappedTypeNode extends TypeNode, RealDeclaration { kind: SyntaxKind.MappedType; parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; @@ -1485,7 +1405,7 @@ namespace ts { * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) */ - export interface ObjectLiteralExpressionBase extends PrimaryExpression, DeclarationBase { + export interface ObjectLiteralExpressionBase extends PrimaryExpression, RealDeclaration { properties: NodeArray; } @@ -1499,7 +1419,7 @@ namespace ts { export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - export interface PropertyAccessExpression extends MemberExpression, DeclarationBase { + export interface PropertyAccessExpression extends MemberExpression, RealDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1531,7 +1451,7 @@ namespace ts { | SuperElementAccessExpression ; - export interface CallExpression extends LeftHandSideExpression, DeclarationBase { + export interface CallExpression extends LeftHandSideExpression, RealDeclaration { kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1550,7 +1470,7 @@ namespace ts { typeArguments?: NodeArray; } - export interface NewExpression extends PrimaryExpression, DeclarationBase { + export interface NewExpression extends PrimaryExpression, RealDeclaration { kind: SyntaxKind.NewExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1608,7 +1528,6 @@ namespace ts { export type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; export interface JsxAttributes extends ObjectLiteralExpressionBase { - kind: SyntaxKind.JsxAttributes; parent?: JsxOpeningLikeElement; } @@ -1845,10 +1764,7 @@ namespace ts { export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - export interface ClassLikeDeclaration extends DeclarationBase { - kind: - | SyntaxKind.ClassDeclaration - | SyntaxKind.ClassExpression; + export interface ClassLikeDeclaration extends RealDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1864,30 +1780,12 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export interface ClassElement extends DeclarationBase { - kind: - | SyntaxKind.PropertyDeclaration - | SyntaxKind.MethodDeclaration - | SyntaxKind.Constructor - | SyntaxKind.SemicolonClassElement - | SyntaxKind.GetAccessor - | SyntaxKind.SetAccessor - | SyntaxKind.IndexSignature - | SyntaxKind.MissingDeclaration; + export interface ClassElement extends RealDeclaration { _classElementBrand: any; name?: PropertyName; } - export interface TypeElement extends DeclarationBase { - kind: - | SyntaxKind.CallSignature - | SyntaxKind.ConstructSignature - | SyntaxKind.PropertySignature - | SyntaxKind.MethodSignature - | SyntaxKind.IndexSignature - | SyntaxKind.MissingDeclaration - | SyntaxKind.JSDocPropertyTag - | SyntaxKind.JSDocRecordMember; + export interface TypeElement extends RealDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1915,7 +1813,7 @@ namespace ts { type: TypeNode; } - export interface EnumMember extends DeclarationBase { + export interface EnumMember extends RealDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; // This does include ComputedPropertyName, but the parser will give an error @@ -2004,14 +1902,14 @@ namespace ts { // import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns } // import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} // import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} - export interface ImportClause extends DeclarationBase { + export interface ImportClause extends RealDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; // Default binding namedBindings?: NamedImportBindings; } - export interface NamespaceImport extends DeclarationBase { + export interface NamespaceImport extends RealDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -2044,14 +1942,14 @@ namespace ts { export type NamedImportsOrExports = NamedImports | NamedExports; - export interface ImportSpecifier extends DeclarationBase { + export interface ImportSpecifier extends RealDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) name: Identifier; // Declared name } - export interface ExportSpecifier extends DeclarationBase { + export interface ExportSpecifier extends RealDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) @@ -2217,7 +2115,7 @@ namespace ts { typeExpression: JSDocTypeExpression; } - export interface JSDocTypedefTag extends JSDocTag, DeclarationBase { + export interface JSDocTypedefTag extends JSDocTag, RealDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2351,7 +2249,7 @@ namespace ts { // Source files are declarations when they are external modules. - export interface SourceFile extends DeclarationBase { + export interface SourceFile extends RealDeclaration { kind: SyntaxKind.SourceFile; statements: NodeArray; endOfFileToken: Token; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 7b92dbf68b5..a3525ee0a70 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -566,7 +566,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.TypeAliasDeclaration: - errorNode = (node).name; + errorNode = (node).name; break; case SyntaxKind.ArrowFunction: return getErrorSpanForArrowFunction(sourceFile, node); @@ -1781,7 +1781,7 @@ namespace ts { return undefined; } if (declaration.kind === SyntaxKind.BinaryExpression) { - const kind = getSpecialPropertyAssignmentKind(declaration); + const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression); const lhs = (declaration as BinaryExpression).left; switch (kind) { case SpecialPropertyAssignmentKind.None: @@ -1806,7 +1806,6 @@ namespace ts { } } - export function isLiteralComputedPropertyDeclarationName(node: Node) { return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) && node.parent.kind === SyntaxKind.ComputedPropertyName && @@ -1827,7 +1826,7 @@ namespace ts { case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyAccessExpression: // Name in member declaration or property name in property access - return (parent).name === node; + return (parent).name === node; case SyntaxKind.QualifiedName: // Name on right hand side of dot in a type query if ((parent).right === node) { @@ -4103,7 +4102,7 @@ namespace ts { || kind === SyntaxKind.MergeDeclarationMarker; } - export function isDeclaration(node: Node): node is DeclarationBase { + export function isDeclaration(node: Node): node is RealDeclaration { return isDeclarationKind(node.kind); } From 9392342f7807c28738199ce82c73e52ac3bc73ef Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 8 May 2017 15:07:50 -0700 Subject: [PATCH 127/282] Switch to Declaration/NamedDeclaration hierarchy --- src/compiler/binder.ts | 12 +++--- src/compiler/checker.ts | 12 +++--- src/compiler/transformers/es2015.ts | 2 +- src/compiler/types.ts | 60 ++++++++++++++--------------- src/compiler/utilities.ts | 10 ++--- src/services/completions.ts | 2 +- src/services/navigateTo.ts | 2 +- 7 files changed, 50 insertions(+), 50 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 38cb93bff7e..b6074162fff 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -304,7 +304,7 @@ namespace ts { } function getDisplayName(node: Declaration): string { - return (node as RealDeclaration).name ? declarationNameToString((node as RealDeclaration).name) : getDeclarationName(node); + return (node as NamedDeclaration).name ? declarationNameToString((node as NamedDeclaration).name) : getDeclarationName(node); } /** @@ -367,8 +367,8 @@ namespace ts { symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } else { - if ((node as RealDeclaration).name) { - (node as RealDeclaration).name.parent = node; + if ((node as NamedDeclaration).name) { + (node as NamedDeclaration).name.parent = node; } // Report errors every position with duplicate declaration @@ -440,9 +440,9 @@ namespace ts { // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag && - node.name && - node.name.kind === SyntaxKind.Identifier && - (node.name).isInJSDocNamespace; + (node as JSDocTypedefTag).name && + (node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier && + ((node as JSDocTypedefTag).name as Identifier).isInJSDocNamespace; if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefInJSDocNamespace) { const exportKind = (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f7d7a79f9a0..76a1616ce3d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3637,8 +3637,8 @@ namespace ts { case SyntaxKind.BindingElement: return isDeclarationVisible(node.parent.parent); case SyntaxKind.VariableDeclaration: - if (isBindingPattern(node.name) && - !(node.name).elements.length) { + if (isBindingPattern((node as VariableDeclaration).name) && + !((node as VariableDeclaration).name as BindingPattern).elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } @@ -6236,8 +6236,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return (node).name.kind === SyntaxKind.ComputedPropertyName - && traverse((node).name); + return (node).name.kind === SyntaxKind.ComputedPropertyName + && traverse((node).name); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && forEachChild(node, traverse); @@ -9925,7 +9925,7 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - if (!declaration.name) { + if (!(declaration as NamedDeclaration).name) { error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } @@ -21909,7 +21909,7 @@ namespace ts { function isTypeDeclarationName(name: Node): boolean { return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && - (name.parent).name === name; + (name.parent).name === name; } function isTypeDeclaration(node: Node): boolean { diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 188da04b36c..cd3f1310100 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -3748,7 +3748,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.VariableDeclaration: - return (parent).name === node + return (parent).name === node && resolver.isDeclarationWithCollidingName(parent); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 51e9d6717ee..63879d76ffa 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -603,15 +603,15 @@ namespace ts { export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; - export interface RealDeclaration extends Node { + export interface Declaration extends Node { _declarationBrand: any; + } + + export interface NamedDeclaration extends Declaration { name?: DeclarationName; } - // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files - export type Declaration = RealDeclaration | BinaryExpression; - - export interface DeclarationStatement extends RealDeclaration, Statement { + export interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } @@ -625,7 +625,7 @@ namespace ts { expression: LeftHandSideExpression; } - export interface TypeParameterDeclaration extends RealDeclaration { + export interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -636,7 +636,7 @@ namespace ts { expression?: Expression; } - export interface SignatureDeclaration extends RealDeclaration { + export interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -653,7 +653,7 @@ namespace ts { export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends RealDeclaration { + export interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; // Declared variable name @@ -667,7 +667,7 @@ namespace ts { declarations: NodeArray; } - export interface ParameterDeclaration extends RealDeclaration { + export interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; // Present on rest parameter @@ -677,7 +677,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface BindingElement extends RealDeclaration { + export interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; // Binding property name (in object binding pattern) @@ -702,7 +702,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface ObjectLiteralElement extends RealDeclaration { + export interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -746,7 +746,7 @@ namespace ts { // SyntaxKind.ShorthandPropertyAssignment // SyntaxKind.EnumMember // SyntaxKind.JSDocPropertyTag - export interface VariableLikeDeclaration extends RealDeclaration { + export interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -755,7 +755,7 @@ namespace ts { initializer?: Expression; } - export interface PropertyLikeDeclaration extends RealDeclaration { + export interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -904,7 +904,7 @@ namespace ts { } // A TypeLiteral is the declaration node for an anonymous symbol. - export interface TypeLiteralNode extends TypeNode, RealDeclaration { + export interface TypeLiteralNode extends TypeNode, NamedDeclaration { kind: SyntaxKind.TypeLiteral; members: NodeArray; } @@ -948,7 +948,7 @@ namespace ts { indexType: TypeNode; } - export interface MappedTypeNode extends TypeNode, RealDeclaration { + export interface MappedTypeNode extends TypeNode, NamedDeclaration { kind: SyntaxKind.MappedType; parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; @@ -1219,7 +1219,7 @@ namespace ts { export type BinaryOperatorToken = Token; - export interface BinaryExpression extends Expression { + export interface BinaryExpression extends Expression, Declaration { kind: SyntaxKind.BinaryExpression; left: Expression; operatorToken: BinaryOperatorToken; @@ -1405,7 +1405,7 @@ namespace ts { * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) */ - export interface ObjectLiteralExpressionBase extends PrimaryExpression, RealDeclaration { + export interface ObjectLiteralExpressionBase extends PrimaryExpression, NamedDeclaration { properties: NodeArray; } @@ -1419,7 +1419,7 @@ namespace ts { export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - export interface PropertyAccessExpression extends MemberExpression, RealDeclaration { + export interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1451,7 +1451,7 @@ namespace ts { | SuperElementAccessExpression ; - export interface CallExpression extends LeftHandSideExpression, RealDeclaration { + export interface CallExpression extends LeftHandSideExpression, NamedDeclaration { kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1470,7 +1470,7 @@ namespace ts { typeArguments?: NodeArray; } - export interface NewExpression extends PrimaryExpression, RealDeclaration { + export interface NewExpression extends PrimaryExpression, NamedDeclaration { kind: SyntaxKind.NewExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1764,7 +1764,7 @@ namespace ts { export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - export interface ClassLikeDeclaration extends RealDeclaration { + export interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1780,12 +1780,12 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export interface ClassElement extends RealDeclaration { + export interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - export interface TypeElement extends RealDeclaration { + export interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1813,7 +1813,7 @@ namespace ts { type: TypeNode; } - export interface EnumMember extends RealDeclaration { + export interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; // This does include ComputedPropertyName, but the parser will give an error @@ -1902,14 +1902,14 @@ namespace ts { // import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns } // import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} // import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} - export interface ImportClause extends RealDeclaration { + export interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; // Default binding namedBindings?: NamedImportBindings; } - export interface NamespaceImport extends RealDeclaration { + export interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1942,14 +1942,14 @@ namespace ts { export type NamedImportsOrExports = NamedImports | NamedExports; - export interface ImportSpecifier extends RealDeclaration { + export interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) name: Identifier; // Declared name } - export interface ExportSpecifier extends RealDeclaration { + export interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) @@ -2115,7 +2115,7 @@ namespace ts { typeExpression: JSDocTypeExpression; } - export interface JSDocTypedefTag extends JSDocTag, RealDeclaration { + export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2249,7 +2249,7 @@ namespace ts { // Source files are declarations when they are external modules. - export interface SourceFile extends RealDeclaration { + export interface SourceFile extends NamedDeclaration { kind: SyntaxKind.SourceFile; statements: NodeArray; endOfFileToken: Token; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index a3525ee0a70..0dc6c92ed2c 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -566,7 +566,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.TypeAliasDeclaration: - errorNode = (node).name; + errorNode = (node).name; break; case SyntaxKind.ArrowFunction: return getErrorSpanForArrowFunction(sourceFile, node); @@ -1802,7 +1802,7 @@ namespace ts { } } else { - return declaration.name; + return (declaration as NamedDeclaration).name; } } @@ -1826,7 +1826,7 @@ namespace ts { case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyAccessExpression: // Name in member declaration or property name in property access - return (parent).name === node; + return (parent).name === node; case SyntaxKind.QualifiedName: // Name on right hand side of dot in a type query if ((parent).right === node) { @@ -2790,7 +2790,7 @@ namespace ts { forEach(declarations, (member: Declaration) => { if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) && hasModifier(member, ModifierFlags.Static) === hasModifier(accessor, ModifierFlags.Static)) { - const memberName = getPropertyNameForPropertyNameNode(member.name); + const memberName = getPropertyNameForPropertyNameNode((member as NamedDeclaration).name); const accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { if (!firstAccessor) { @@ -4102,7 +4102,7 @@ namespace ts { || kind === SyntaxKind.MergeDeclarationMarker; } - export function isDeclaration(node: Node): node is RealDeclaration { + export function isDeclaration(node: Node): node is NamedDeclaration { return isDeclarationKind(node.kind); } diff --git a/src/services/completions.ts b/src/services/completions.ts index 6ac3762b4c7..b9d62df751e 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1214,7 +1214,7 @@ namespace ts.Completions { // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = (m.name).text; + existingName = (getNameOfDeclaration(m) as Identifier).text; } existingMemberNames.set(existingName, true); diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index c29b29143c5..2fdc567b9bb 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -52,7 +52,7 @@ namespace ts.NavigateTo { rawItems = filter(rawItems, item => { const decl = item.declaration; if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) { - const importer = checker.getSymbolAtLocation(decl.name); + const importer = checker.getSymbolAtLocation((decl as NamedDeclaration).name); const imported = checker.getAliasedSymbol(importer); return importer.name !== imported.name; } From 36ef849209be5e8ef4ec40354ffdeea7bc84f298 Mon Sep 17 00:00:00 2001 From: Yui T Date: Mon, 8 May 2017 15:35:17 -0700 Subject: [PATCH 128/282] Update baaselines --- ...FunctionComponentsWithTypeArguments5.errors.txt | 2 +- ...tatelessFunctionComponentsWithTypeArguments5.js | 4 ++-- tests/cases/fourslash/tsxQuickInfo6.ts | 4 ++-- tests/cases/fourslash/tsxQuickInfo7.ts | 14 +++++++------- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt index 3f5623921fd..b92375797e7 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt @@ -6,7 +6,7 @@ tests/cases/conformance/jsx/file.tsx(16,42): error TS2339: Property 'prop1' does declare function Component(l: U): JSX.Element; function createComponent(arg: T) { - // let a1 = ; + let a1 = ; let a2 = ; } diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js index e77e79ee732..7e3c8bf35d2 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.js @@ -3,7 +3,7 @@ import React = require('react') declare function Component(l: U): JSX.Element; function createComponent(arg: T) { - // let a1 = ; + let a1 = ; let a2 = ; } @@ -23,7 +23,7 @@ define(["require", "exports", "react"], function (require, exports, React) { "use strict"; exports.__esModule = true; function createComponent(arg) { - // let a1 = ; + var a1 = ; var a2 = ; } function Bar(arg) { diff --git a/tests/cases/fourslash/tsxQuickInfo6.ts b/tests/cases/fourslash/tsxQuickInfo6.ts index e121e52c0aa..88d9435e801 100644 --- a/tests/cases/fourslash/tsxQuickInfo6.ts +++ b/tests/cases/fourslash/tsxQuickInfo6.ts @@ -14,6 +14,6 @@ //// } verify.quickInfos({ - 1: "function ComponentSpecific<{}>(l: {\n prop: {};\n}): any", - 2: "function ComponentSpecific<{}>(l: {\n prop: {};\n}): any" + 1: "function ComponentSpecific(l: {\n prop: number;\n}): any", + 2: "function ComponentSpecific<\"hello\">(l: {\n prop: \"hello\";\n}): any" }); diff --git a/tests/cases/fourslash/tsxQuickInfo7.ts b/tests/cases/fourslash/tsxQuickInfo7.ts index ca90d83d719..3e66fb655f1 100644 --- a/tests/cases/fourslash/tsxQuickInfo7.ts +++ b/tests/cases/fourslash/tsxQuickInfo7.ts @@ -15,15 +15,15 @@ //// let a3 = ; //// let a4 = ; //// let a5 = ; -//// let a6 = ; +//// let a6 = ; //// } verify.quickInfos({ - 1: "function OverloadComponent(): any (+2 overloads)", - 2: "function OverloadComponent(): any (+2 overloads)", - 3: "function OverloadComponent(): any (+2 overloads)", - 4: "function OverloadComponent(): any (+2 overloads)", + 1: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", + 2: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", + 3: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", + 4: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", 5: "function OverloadComponent(): any (+2 overloads)", - 6: "function OverloadComponent(): any (+2 overloads)", - 7: "function OverloadComponent(): any (+2 overloads)" + 6: "function OverloadComponent(attr: {\n b: number;\n a: boolean;\n}): any (+2 overloads)", + 7: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)" }); From 3b676f430826972ce56fcbf570089aa145714c07 Mon Sep 17 00:00:00 2001 From: Yui T Date: Mon, 8 May 2017 15:35:26 -0700 Subject: [PATCH 129/282] Fix linting error --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e544b9239f6..abbbad789ac 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13285,7 +13285,7 @@ namespace ts { attributesArray = []; attributesTable = createMap(); } - const exprType = getApparentType(checkExpression(attributeDecl.expression)) + const exprType = getApparentType(checkExpression(attributeDecl.expression)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } From d9b68e92138faea04316356875bca8e9630f0042 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 8 May 2017 16:26:57 -0700 Subject: [PATCH 130/282] Type Literal and Binding Name formatting --- src/compiler/checker.ts | 25 ++++++++++++++++++++++--- src/compiler/emitter.ts | 9 +++++---- src/compiler/types.ts | 2 ++ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1fae8206f49..658bad82f83 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2602,7 +2602,8 @@ namespace ts { context.inObjectTypeLiteral = true; const members = createTypeNodesFromResolvedType(resolved); context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return createTypeLiteralNode(members); + const typeLiteralNode = createTypeLiteralNode(members); + return setEmitFlags(typeLiteralNode, EmitFlags.ToStringFormatting); } function shouldAddParenthesisAroundFunctionType(callSignature: Signature, context: NodeBuilderContext) { @@ -2811,8 +2812,14 @@ namespace ts { const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); const parameterType = getTypeOfSymbol(parameterSymbol); const parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - const name = getDeepSynthesizedClone(parameterDeclaration.name); - + let name: BindingName; + if (parameterDeclaration.name.kind === SyntaxKind.Identifier) { + name = getSynthesizedClone(parameterDeclaration.name); + } + else { + Debug.assert(parameterDeclaration.name.kind === SyntaxKind.ArrayBindingPattern || parameterDeclaration.name.kind === SyntaxKind.ObjectBindingPattern); + name = cloneBindingName(parameterDeclaration.name); + } let questionToken: Token | undefined; let initializer: Expression | undefined; if (isOptionalParameter(parameterDeclaration)) { @@ -2833,6 +2840,18 @@ namespace ts { parameterTypeNode, initializer); return parameterNode; + + function cloneBindingName(node: BindingName): BindingName { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node: Node): Node { + const visited = visitEachChild(node, elideInitializerAndSetEmitFlags, nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + const clone = nodeIsSynthesized(visited) ? visited : getSynthesizedClone(visited); + if (clone.kind === SyntaxKind.BindingElement) { + (clone).initializer = undefined; + } + return setEmitFlags(clone, EmitFlags.ToStringFormatting); + } + } } // TODO: add meaning: SymbolFlags argument. diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index cd16074d572..70c9688b60e 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -956,7 +956,7 @@ namespace ts { function emitTypeLiteral(node: TypeLiteralNode) { write("{"); if (node.members.length > 0) { - emitList(node, node.members, ListFormat.SingleLineTypeLiteralMembers); + emitList(node, node.members, getEmitFlags(node) & EmitFlags.ToStringFormatting ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers); } write("}"); } @@ -1037,7 +1037,7 @@ namespace ts { } else { write("{"); - emitList(node, elements, ListFormat.ObjectBindingPatternElements); + emitList(node, elements, getEmitFlags(node) & EmitFlags.ToStringFormatting ? ListFormat.ObjectBindingPatternElements : ListFormat.ObjectBindingPatternElementsWithSpaceBetweenBraces); write("}"); } } @@ -2948,13 +2948,14 @@ namespace ts { // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings, HeritageClauses = SingleLine | SpaceBetweenSiblings, - SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings | Indented, // MultiLine | Indented, + SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings | Indented, MultiLineTypeLiteralMembers = MultiLine | Indented, TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, - ObjectBindingPatternElements = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings, + ObjectBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings, + ObjectBindingPatternElementsWithSpaceBetweenBraces = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings, ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings, ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces, ArrayLiteralExpressionElements = PreserveLines | CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | Indented | SquareBrackets, diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 6c1861a5892..67b73cdbda5 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3943,6 +3943,7 @@ namespace ts { } export const enum EmitFlags { + None = 0, SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node. NoSubstitution = 1 << 2, // Disables further substitution of an expression. @@ -3969,6 +3970,7 @@ namespace ts { NoHoisting = 1 << 20, // Do not hoist this declaration in --module system HasEndOfDeclarationMarker = 1 << 21, // Declaration has an associated NotEmittedStatement to mark the end of the declaration Iterator = 1 << 22, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. + ToStringFormatting = 1 << 23 } export interface EmitHelper { From 51c76ac35128adba8a760fc08092e0035a1b5cd5 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 8 May 2017 18:17:17 -0700 Subject: [PATCH 131/282] fix malformed nodes --- src/compiler/checker.ts | 6 +++--- src/compiler/factory.ts | 4 ++++ src/compiler/utilities.ts | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 658bad82f83..9ac1dc2d615 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2752,7 +2752,7 @@ namespace ts { function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword); - const name = getNameFromIndexInfo(indexInfo); + const name = getNameFromIndexInfo(indexInfo) || "x"; const indexingParameter = createParameter( /*decorators*/ undefined, @@ -2830,8 +2830,8 @@ namespace ts { initializer = parameterDeclaration.initializer; } const parameterNode = createParameter( - parameterDeclaration.decorators, - parameterDeclaration.modifiers, + /*decorators*/ undefined, + cloneNodeArray(parameterDeclaration.modifiers), (parameterDeclaration ? isRestParameter(parameterDeclaration) : isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) ? createToken(SyntaxKind.DotDotDotToken) : undefined, diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 172710f39aa..45b09892bb0 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -89,6 +89,10 @@ namespace ts { return nodeIsSynthesized(clone) ? clone : getSynthesizedClone(clone); } + export function cloneNodeArray(nodeArray: NodeArray) { + return nodeArray && nodeArray.map(getDeepSynthesizedClone); + } + // Literals export function createLiteral(value: string): StringLiteral; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index cd63ebfb690..baa83697fba 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -466,7 +466,7 @@ namespace ts { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } - export function getNameFromIndexInfo(info: IndexInfo) { + export function getNameFromIndexInfo(info: IndexInfo): string | undefined { return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } From ccec13aaf151d444defe42fde6860ffddb8cc6f1 Mon Sep 17 00:00:00 2001 From: Andrew Stegmaier Date: Mon, 8 May 2017 23:56:29 -0700 Subject: [PATCH 132/282] getOwnPropertyDescriptor return should allow undefined getOwnPropertyDescriptor _should_ return undefined in certain situations. This is documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor This change addresses https://github.com/Microsoft/TypeScript/issues/14923 and https://github.com/Microsoft/TypeScript/issues/10904. The original fix to 14923 was to the /lib/lib.es2015.proxy.d.ts file instead of /src/lib/lib.es2015.proxy.d.ts (see: https://github.com/Microsoft/TypeScript/pull/10550/commits). I think this meant that the change got over-written by a generation script (see note here: https://github.com/Microsoft/TypeScript/tree/master/lib) --- src/lib/es2015.proxy.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/es2015.proxy.d.ts b/src/lib/es2015.proxy.d.ts index 34aedce0128..67595021346 100644 --- a/src/lib/es2015.proxy.d.ts +++ b/src/lib/es2015.proxy.d.ts @@ -3,7 +3,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; From 318ccf24b501eef627104adbe119983ca5bd486c Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 9 May 2017 09:08:58 -0700 Subject: [PATCH 133/282] importTracker: Require calls are stored in `sourceFile.imports`, no need to search for them --- src/services/importTracker.ts | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index c94d5cc3143..f85f5961aaa 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -330,7 +330,7 @@ namespace ts.FindAllReferences { /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile: SourceFile, action: (importStatement: ImporterOrCallExpression, imported: StringLiteral) => void): void { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (const moduleSpecifier of sourceFile.imports) { action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); } @@ -358,27 +358,21 @@ namespace ts.FindAllReferences { } } }); - - if (sourceFile.flags & NodeFlags.JavaScriptFile) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node: Node): void { - if (isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0] as StringLiteral); - } else { - node.forEachChild(recur); - } - }); - } } } - function importerFromModuleSpecifier(moduleSpecifier: StringLiteral): Importer { + function importerFromModuleSpecifier(moduleSpecifier: StringLiteral): ImporterOrCallExpression { const decl = moduleSpecifier.parent; - if (decl.kind === SyntaxKind.ImportDeclaration || decl.kind === SyntaxKind.ExportDeclaration) { - return decl as ImportDeclaration | ExportDeclaration; + switch (decl.kind) { + case SyntaxKind.CallExpression: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + return decl as ImportDeclaration | ExportDeclaration | CallExpression; + case SyntaxKind.ExternalModuleReference: + return (decl as ExternalModuleReference).parent; + default: + Debug.assert(false); } - Debug.assert(decl.kind === SyntaxKind.ExternalModuleReference); - return (decl as ExternalModuleReference).parent; } export interface ImportedSymbol { From 157b777660b7e65d8e2d9cf871bd7f9c1aba5bbe Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 9 May 2017 10:46:47 -0700 Subject: [PATCH 134/282] Unnamed nodes now extend Declaration, not NamedDeclaration --- src/compiler/types.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a6c04616652..4bd44a89f4d 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -904,7 +904,7 @@ namespace ts { } // A TypeLiteral is the declaration node for an anonymous symbol. - export interface TypeLiteralNode extends TypeNode, NamedDeclaration { + export interface TypeLiteralNode extends TypeNode, Declaration { kind: SyntaxKind.TypeLiteral; members: NodeArray; } @@ -948,7 +948,7 @@ namespace ts { indexType: TypeNode; } - export interface MappedTypeNode extends TypeNode, NamedDeclaration { + export interface MappedTypeNode extends TypeNode, Declaration { kind: SyntaxKind.MappedType; parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; @@ -1405,7 +1405,7 @@ namespace ts { * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) */ - export interface ObjectLiteralExpressionBase extends PrimaryExpression, NamedDeclaration { + export interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { properties: NodeArray; } @@ -1451,7 +1451,7 @@ namespace ts { | SuperElementAccessExpression ; - export interface CallExpression extends LeftHandSideExpression, NamedDeclaration { + export interface CallExpression extends LeftHandSideExpression, Declaration { kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -1470,7 +1470,7 @@ namespace ts { typeArguments?: NodeArray; } - export interface NewExpression extends PrimaryExpression, NamedDeclaration { + export interface NewExpression extends PrimaryExpression, Declaration { kind: SyntaxKind.NewExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; @@ -2249,7 +2249,7 @@ namespace ts { // Source files are declarations when they are external modules. - export interface SourceFile extends NamedDeclaration { + export interface SourceFile extends Declaration { kind: SyntaxKind.SourceFile; statements: NodeArray; endOfFileToken: Token; From ac68e8d6f12ec81eda832d1f67ee6ff438e58cd8 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 9 May 2017 11:09:20 -0700 Subject: [PATCH 135/282] initializer issues --- src/compiler/checker.ts | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9ac1dc2d615..9410402d372 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2810,7 +2810,10 @@ namespace ts { function symbolToParameterDeclaration(parameterSymbol: Symbol, context: NodeBuilderContext): ParameterDeclaration { const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); - const parameterType = getTypeOfSymbol(parameterSymbol); + let parameterType = getTypeOfSymbol(parameterSymbol); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = includeFalsyTypes(parameterType, TypeFlags.Undefined); + } const parameterTypeNode = typeToTypeNodeHelper(parameterType, context); let name: BindingName; if (parameterDeclaration.name.kind === SyntaxKind.Identifier) { @@ -2820,25 +2823,19 @@ namespace ts { Debug.assert(parameterDeclaration.name.kind === SyntaxKind.ArrayBindingPattern || parameterDeclaration.name.kind === SyntaxKind.ObjectBindingPattern); name = cloneBindingName(parameterDeclaration.name); } - let questionToken: Token | undefined; - let initializer: Expression | undefined; - if (isOptionalParameter(parameterDeclaration)) { - questionToken = createToken(SyntaxKind.QuestionToken); - } - else { - // TODO(aozgaa): In the future, check initializer accessibility. - initializer = parameterDeclaration.initializer; - } + const questionToken = isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : undefined; + const dotDotDotToken = (parameterDeclaration ? isRestParameter(parameterDeclaration) : isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) ? + createToken(SyntaxKind.DotDotDotToken) : + undefined; + const parameterNode = createParameter( /*decorators*/ undefined, cloneNodeArray(parameterDeclaration.modifiers), - (parameterDeclaration ? isRestParameter(parameterDeclaration) : isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) ? - createToken(SyntaxKind.DotDotDotToken) : - undefined, + dotDotDotToken, name, questionToken, parameterTypeNode, - initializer); + /*initializer*/ undefined); return parameterNode; function cloneBindingName(node: BindingName): BindingName { From a2dec0d03dd03849346cc1bf5569a28aa4ee6c99 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 9 May 2017 12:01:10 -0700 Subject: [PATCH 136/282] Fix #15062: report errors for parameter properties in private constructors --- src/compiler/declarationEmitter.ts | 11 ++- .../classConstructorAccessibility.js | 2 +- .../classConstructorAccessibility2.js | 2 +- .../classConstructorAccessibility3.js | 2 +- .../classConstructorOverloadsAccessibility.js | 2 +- .../declarationEmitClassPrivateConstructor.js | 72 +++++++++++++++++++ ...arationEmitClassPrivateConstructor.symbols | 38 ++++++++++ ...clarationEmitClassPrivateConstructor.types | 38 ++++++++++ ...ionEmitClassPrivateConstructor2.errors.txt | 20 ++++++ ...declarationEmitClassPrivateConstructor2.js | 29 ++++++++ .../reference/typesWithPrivateConstructor.js | 2 +- .../declarationEmitClassPrivateConstructor.ts | 22 ++++++ ...declarationEmitClassPrivateConstructor2.ts | 15 ++++ 13 files changed, 248 insertions(+), 7 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitClassPrivateConstructor.js create mode 100644 tests/baselines/reference/declarationEmitClassPrivateConstructor.symbols create mode 100644 tests/baselines/reference/declarationEmitClassPrivateConstructor.types create mode 100644 tests/baselines/reference/declarationEmitClassPrivateConstructor2.errors.txt create mode 100644 tests/baselines/reference/declarationEmitClassPrivateConstructor2.js create mode 100644 tests/cases/compiler/declarationEmitClassPrivateConstructor.ts create mode 100644 tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index d7ad2c3a78d..3c02fc634b5 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1266,7 +1266,9 @@ namespace ts { Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit - else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) { + // The only exception here is if the constructor was marked as private. we are not emitting the constructor paramters at all. + else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || + (node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (hasModifier(node, ModifierFlags.Static)) { return symbolAccessibilityResult.errorModuleName ? @@ -1275,7 +1277,7 @@ namespace ts { Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === SyntaxKind.ClassDeclaration) { + else if (node.parent.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.Parameter) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -1501,6 +1503,11 @@ namespace ts { write("["); } else { + if (node.kind === SyntaxKind.Constructor && hasModifier(node, ModifierFlags.Private)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) { write("new "); diff --git a/tests/baselines/reference/classConstructorAccessibility.js b/tests/baselines/reference/classConstructorAccessibility.js index 46a548d0b54..4d120a3980f 100644 --- a/tests/baselines/reference/classConstructorAccessibility.js +++ b/tests/baselines/reference/classConstructorAccessibility.js @@ -89,7 +89,7 @@ declare class C { } declare class D { x: number; - private constructor(x); + private constructor(); } declare class E { x: number; diff --git a/tests/baselines/reference/classConstructorAccessibility2.js b/tests/baselines/reference/classConstructorAccessibility2.js index 7297af11a4e..76c8ea19110 100644 --- a/tests/baselines/reference/classConstructorAccessibility2.js +++ b/tests/baselines/reference/classConstructorAccessibility2.js @@ -135,7 +135,7 @@ declare class BaseB { } declare class BaseC { x: number; - private constructor(x); + private constructor(); createInstance(): void; static staticInstance(): void; } diff --git a/tests/baselines/reference/classConstructorAccessibility3.js b/tests/baselines/reference/classConstructorAccessibility3.js index 3e024970bcf..d1bd8f38c40 100644 --- a/tests/baselines/reference/classConstructorAccessibility3.js +++ b/tests/baselines/reference/classConstructorAccessibility3.js @@ -90,7 +90,7 @@ declare class Baz { } declare class Qux { x: number; - private constructor(x); + private constructor(); } declare let a: typeof Foo; declare let b: typeof Baz; diff --git a/tests/baselines/reference/classConstructorOverloadsAccessibility.js b/tests/baselines/reference/classConstructorOverloadsAccessibility.js index 7fef7443c62..2a173966d5d 100644 --- a/tests/baselines/reference/classConstructorOverloadsAccessibility.js +++ b/tests/baselines/reference/classConstructorOverloadsAccessibility.js @@ -59,7 +59,7 @@ var D = (function () { declare class A { constructor(a: boolean); protected constructor(a: number); - private constructor(a); + private constructor(); } declare class B { protected constructor(a: number); diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor.js b/tests/baselines/reference/declarationEmitClassPrivateConstructor.js new file mode 100644 index 00000000000..6cc65964987 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor.js @@ -0,0 +1,72 @@ +//// [declarationEmitClassPrivateConstructor.ts] +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(data: PrivateInterface) { } +} + +export class ExportedClass2 { + private constructor(private data: PrivateInterface) { } +} + +export class ExportedClass3 { + private constructor(private data: PrivateInterface, private n: number) { } +} + +export class ExportedClass4 { + private constructor(private data: PrivateInterface, public n:number) { } +} + +//// [declarationEmitClassPrivateConstructor.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ExportedClass1 = (function () { + function ExportedClass1(data) { + } + return ExportedClass1; +}()); +exports.ExportedClass1 = ExportedClass1; +var ExportedClass2 = (function () { + function ExportedClass2(data) { + this.data = data; + } + return ExportedClass2; +}()); +exports.ExportedClass2 = ExportedClass2; +var ExportedClass3 = (function () { + function ExportedClass3(data, n) { + this.data = data; + this.n = n; + } + return ExportedClass3; +}()); +exports.ExportedClass3 = ExportedClass3; +var ExportedClass4 = (function () { + function ExportedClass4(data, n) { + this.data = data; + this.n = n; + } + return ExportedClass4; +}()); +exports.ExportedClass4 = ExportedClass4; + + +//// [declarationEmitClassPrivateConstructor.d.ts] +export declare class ExportedClass1 { + private constructor(); +} +export declare class ExportedClass2 { + private data; + private constructor(); +} +export declare class ExportedClass3 { + private data; + private n; + private constructor(); +} +export declare class ExportedClass4 { + private data; + n: number; + private constructor(); +} diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor.symbols b/tests/baselines/reference/declarationEmitClassPrivateConstructor.symbols new file mode 100644 index 00000000000..285d9fb3f39 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor.symbols @@ -0,0 +1,38 @@ +=== tests/cases/compiler/declarationEmitClassPrivateConstructor.ts === +interface PrivateInterface { +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +} + +export class ExportedClass1 { +>ExportedClass1 : Symbol(ExportedClass1, Decl(declarationEmitClassPrivateConstructor.ts, 1, 1)) + + private constructor(data: PrivateInterface) { } +>data : Symbol(data, Decl(declarationEmitClassPrivateConstructor.ts, 4, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +} + +export class ExportedClass2 { +>ExportedClass2 : Symbol(ExportedClass2, Decl(declarationEmitClassPrivateConstructor.ts, 5, 1)) + + private constructor(private data: PrivateInterface) { } +>data : Symbol(ExportedClass2.data, Decl(declarationEmitClassPrivateConstructor.ts, 8, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +} + +export class ExportedClass3 { +>ExportedClass3 : Symbol(ExportedClass3, Decl(declarationEmitClassPrivateConstructor.ts, 9, 1)) + + private constructor(private data: PrivateInterface, private n: number) { } +>data : Symbol(ExportedClass3.data, Decl(declarationEmitClassPrivateConstructor.ts, 12, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +>n : Symbol(ExportedClass3.n, Decl(declarationEmitClassPrivateConstructor.ts, 12, 55)) +} + +export class ExportedClass4 { +>ExportedClass4 : Symbol(ExportedClass4, Decl(declarationEmitClassPrivateConstructor.ts, 13, 1)) + + private constructor(private data: PrivateInterface, public n:number) { } +>data : Symbol(ExportedClass4.data, Decl(declarationEmitClassPrivateConstructor.ts, 16, 24)) +>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0)) +>n : Symbol(ExportedClass4.n, Decl(declarationEmitClassPrivateConstructor.ts, 16, 55)) +} diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor.types b/tests/baselines/reference/declarationEmitClassPrivateConstructor.types new file mode 100644 index 00000000000..ed8d5494ba6 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor.types @@ -0,0 +1,38 @@ +=== tests/cases/compiler/declarationEmitClassPrivateConstructor.ts === +interface PrivateInterface { +>PrivateInterface : PrivateInterface +} + +export class ExportedClass1 { +>ExportedClass1 : ExportedClass1 + + private constructor(data: PrivateInterface) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +} + +export class ExportedClass2 { +>ExportedClass2 : ExportedClass2 + + private constructor(private data: PrivateInterface) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +} + +export class ExportedClass3 { +>ExportedClass3 : ExportedClass3 + + private constructor(private data: PrivateInterface, private n: number) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +>n : number +} + +export class ExportedClass4 { +>ExportedClass4 : ExportedClass4 + + private constructor(private data: PrivateInterface, public n:number) { } +>data : PrivateInterface +>PrivateInterface : PrivateInterface +>n : number +} diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor2.errors.txt b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.errors.txt new file mode 100644 index 00000000000..a31454a4760 --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.errors.txt @@ -0,0 +1,20 @@ +tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts(5,38): error TS4031: Public property 'data' of exported class has or is using private name 'PrivateInterface'. +tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts(10,33): error TS4063: Parameter 'data' of constructor from exported class has or is using private name 'PrivateInterface'. + + +==== tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts (2 errors) ==== + interface PrivateInterface { + } + + export class ExportedClass1 { + private constructor(public data: PrivateInterface) { } + ~~~~~~~~~~~~~~~~ +!!! error TS4031: Public property 'data' of exported class has or is using private name 'PrivateInterface'. + } + + + export class ExportedClass2 { + protected constructor(data: PrivateInterface) { } + ~~~~~~~~~~~~~~~~ +!!! error TS4063: Parameter 'data' of constructor from exported class has or is using private name 'PrivateInterface'. + } \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitClassPrivateConstructor2.js b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.js new file mode 100644 index 00000000000..8b7ad25a6bf --- /dev/null +++ b/tests/baselines/reference/declarationEmitClassPrivateConstructor2.js @@ -0,0 +1,29 @@ +//// [declarationEmitClassPrivateConstructor2.ts] +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(public data: PrivateInterface) { } +} + + +export class ExportedClass2 { + protected constructor(data: PrivateInterface) { } +} + +//// [declarationEmitClassPrivateConstructor2.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ExportedClass1 = (function () { + function ExportedClass1(data) { + this.data = data; + } + return ExportedClass1; +}()); +exports.ExportedClass1 = ExportedClass1; +var ExportedClass2 = (function () { + function ExportedClass2(data) { + } + return ExportedClass2; +}()); +exports.ExportedClass2 = ExportedClass2; diff --git a/tests/baselines/reference/typesWithPrivateConstructor.js b/tests/baselines/reference/typesWithPrivateConstructor.js index be58c77339d..e5c59b99e93 100644 --- a/tests/baselines/reference/typesWithPrivateConstructor.js +++ b/tests/baselines/reference/typesWithPrivateConstructor.js @@ -38,7 +38,7 @@ declare class C { declare var c: any; declare var r: () => void; declare class C2 { - private constructor(x); + private constructor(); } declare var c2: any; declare var r2: (x: number) => void; diff --git a/tests/cases/compiler/declarationEmitClassPrivateConstructor.ts b/tests/cases/compiler/declarationEmitClassPrivateConstructor.ts new file mode 100644 index 00000000000..d77360496c9 --- /dev/null +++ b/tests/cases/compiler/declarationEmitClassPrivateConstructor.ts @@ -0,0 +1,22 @@ +// @target: es5 +// @module: commonjs +// @declaration: true + +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(data: PrivateInterface) { } +} + +export class ExportedClass2 { + private constructor(private data: PrivateInterface) { } +} + +export class ExportedClass3 { + private constructor(private data: PrivateInterface, private n: number) { } +} + +export class ExportedClass4 { + private constructor(private data: PrivateInterface, public n:number) { } +} \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts b/tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts new file mode 100644 index 00000000000..900ece84f8e --- /dev/null +++ b/tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts @@ -0,0 +1,15 @@ +// @target: es5 +// @module: commonjs +// @declaration: true + +interface PrivateInterface { +} + +export class ExportedClass1 { + private constructor(public data: PrivateInterface) { } +} + + +export class ExportedClass2 { + protected constructor(data: PrivateInterface) { } +} \ No newline at end of file From e0438db63eaadddf6cf1f8822fb588d4f26eaaff Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 9 May 2017 12:57:22 -0700 Subject: [PATCH 137/282] Parenthesize function types --- src/compiler/checker.ts | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9410402d372..439874cf987 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2359,6 +2359,8 @@ namespace ts { context.InElementType = false; const inTypeAlias = context.InTypeAlias; context.InTypeAlias = false; + const inFirstTypeArgument = context.InFirstTypeArgument; + context.InFirstTypeArgument = false; // TODO: should be assert? if (!type) { @@ -2367,8 +2369,6 @@ namespace ts { return undefined; } - - if (type.flags & TypeFlags.Any) { return createKeywordTypeNode(SyntaxKind.AnyKeyword); } @@ -2586,15 +2586,18 @@ namespace ts { if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; - const functionTypeNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); + const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); return shouldAddParenthesisAroundFunctionType(signature, context) ? - createParenthesizedTypeNode(functionTypeNode) : - functionTypeNode; + createParenthesizedTypeNode(signatureNode) : + signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { const signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context); + const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context); + return shouldAddParenthesisAroundFunctionType(signature, context) ? + createParenthesizedTypeNode(signatureNode) : + signatureNode; } } @@ -2610,7 +2613,7 @@ namespace ts { if (InElementType) { return true; } - else if (context.InFirstTypeArgument) { + else if (inFirstTypeArgument) { // Add parenthesis around function type for the first type argument to avoid ambiguity const typeParameters = callSignature.target && (context.flags & NodeBuilderFlags.WriteTypeArgumentsOfSignature) ? callSignature.target.typeParameters : callSignature.typeParameters; @@ -2690,7 +2693,14 @@ namespace ts { entityName = nameIdentifier; } const typeParameterCount = (type.target.typeParameters || emptyArray).length; - const typeArgumentNodes = some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i), /*addInElementTypeFlag*/ false) : undefined; + + let typeArgumentNodes: TypeNode[] | undefined; + if (some(typeArguments)) { + const slice = typeArguments.slice(i, typeParameterCount - i); + context.InFirstTypeArgument = true; + typeArgumentNodes = mapToTypeNodeArray(slice, /*addInElementTypeFlag*/ false); + } + return createTypeReferenceNode(entityName, typeArgumentNodes); } } @@ -2851,7 +2861,6 @@ namespace ts { } } - // TODO: add meaning: SymbolFlags argument. // TODO: add SymbolFormatFlags?? Yes to add outer type parameters. Defer UseOnlyExternalAliasing until a separate symbolbuilder PR. function symbolToName(symbol: Symbol, expectsIdentifier: true, meaning: SymbolFlags, context: NodeBuilderContext): Identifier; function symbolToName(symbol: Symbol, expectsIdentifier: false, meaning: SymbolFlags, context: NodeBuilderContext): EntityName; From 89f8cca488361b8385861792f13b87606802fbb8 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 9 May 2017 13:14:39 -0700 Subject: [PATCH 138/282] mapped type indent --- src/compiler/checker.ts | 3 ++- src/compiler/emitter.ts | 19 +++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 439874cf987..f06afe4425d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2516,7 +2516,8 @@ namespace ts { const readonlyToken = type.declaration && type.declaration.readonlyToken ? createToken(SyntaxKind.ReadonlyKeyword) : undefined; const questionToken = type.declaration && type.declaration.questionToken ? createToken(SyntaxKind.QuestionToken) : undefined; - return createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + const mappedTypeNode = createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return setEmitFlags(mappedTypeNode, EmitFlags.SingleLine); } function createAnonymousTypeNode(type: ObjectType): TypeNode { diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 70c9688b60e..11cc83dc15a 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1004,9 +1004,15 @@ namespace ts { } function emitMappedType(node: MappedTypeNode) { + const emitFlags = getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & EmitFlags.SingleLine) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -1017,8 +1023,13 @@ namespace ts { write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & EmitFlags.SingleLine) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } From ad58572edbcd761623a918851e9afa36a733a455 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 9 May 2017 13:50:14 -0700 Subject: [PATCH 139/282] trailing comma --- src/compiler/emitter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 11cc83dc15a..582bc6ed7ab 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2965,7 +2965,7 @@ namespace ts { TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, - ObjectBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings, + ObjectBindingPatternElements = SingleLine | CommaDelimited | SpaceBetweenSiblings, ObjectBindingPatternElementsWithSpaceBetweenBraces = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings, ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings, ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces, From 0349caa5cfec61589af41a7b660714ca062dd2ab Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 9 May 2017 13:54:35 -0700 Subject: [PATCH 140/282] fix typo --- src/compiler/declarationEmitter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 3c02fc634b5..07cb850b01d 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1266,7 +1266,7 @@ namespace ts { Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit - // The only exception here is if the constructor was marked as private. we are not emitting the constructor paramters at all. + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || (node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) { // TODO(jfreeman): Deal with computed properties in error reporting. From 41452a5b2199e17ceb440784a06fd18e60220d8d Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 9 May 2017 18:20:46 -0700 Subject: [PATCH 141/282] add typeArguments to identifier --- src/compiler/checker.ts | 59 ++++++++++++++++++++-------------------- src/compiler/emitter.ts | 1 + src/compiler/factory.ts | 9 +++++- src/compiler/types.ts | 1 + src/compiler/visitor.ts | 3 ++ src/services/services.ts | 1 + 6 files changed, 44 insertions(+), 30 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f06afe4425d..82567bc170d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2449,13 +2449,13 @@ namespace ts { if (!inTypeAlias && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); - const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, /*addInElementTypeFlag*/ false); + const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); return createTypeReferenceNode(name, typeArgumentNodes); } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; - const typeNodes = types && mapToTypeNodeArray(types, /*addInElementTypeFlag*/ true); + const typeNodes = types && mapToTypeNodeArray(types, context, /*addInElementTypeFlag*/ true, /*addInFirstTypeArgumentFlag*/ false); if (typeNodes && typeNodes.length > 0) { const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); return InElementType ? createParenthesizedTypeNode(unionOrIntersectionTypeNode) : unionOrIntersectionTypeNode; @@ -2492,20 +2492,6 @@ namespace ts { Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types: Type[], addInElementTypeFlag: boolean): TypeNode[] { - const result = []; - Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); - for (const type of types) { - context.InElementType = addInElementTypeFlag; - const typeNode = typeToTypeNodeHelper(type, context); - if (typeNode) { - result.push(typeNode); - } - } - Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); - return result; - } - function createMappedTypeNodeFromType(type: MappedType) { Debug.assert(!!(type.flags & TypeFlags.Object)); const typeParameter = getTypeParameterFromMappedType(type); @@ -2642,7 +2628,7 @@ namespace ts { } else if (type.target.objectFlags & ObjectFlags.Tuple) { if (typeArguments.length > 0) { - const tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type)), /*addInElementTypeFlag*/ false); + const tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type)), context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ false); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return createTupleTypeNode(tupleConstituentNodes); } @@ -2669,8 +2655,11 @@ namespace ts { // 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 (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { - // inFirstTypeArgument??? + const qualifiedNamePartTypeArguments = typeArguments.slice(start,i); + const qualifiedNamePartTypeArgumentNodes = qualifiedNamePartTypeArguments && createNodeArray(mapToTypeNodeArray(qualifiedNamePartTypeArguments, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true)); const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true, SymbolFlags.Type, context); + qualifiedNamePart.typeArguments = qualifiedNamePartTypeArgumentNodes; + if (!qualifiedName) { qualifiedName = createQualifiedName(qualifiedNamePart, /*right*/ undefined); } @@ -2699,7 +2688,7 @@ namespace ts { if (some(typeArguments)) { const slice = typeArguments.slice(i, typeParameterCount - i); context.InFirstTypeArgument = true; - typeArgumentNodes = mapToTypeNodeArray(slice, /*addInElementTypeFlag*/ false); + typeArgumentNodes = mapToTypeNodeArray(slice, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); } return createTypeReferenceNode(entityName, typeArgumentNodes); @@ -2761,6 +2750,24 @@ namespace ts { } } + function mapToTypeNodeArray(types: Type[], context: NodeBuilderContext, addInElementTypeFlag: boolean, addInFirstTypeArgumentFlag: boolean): TypeNode[] { + const result = []; + Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); + for (let i = 0; i < types.length; ++i) { + let type = types[i] + context.InElementType = addInElementTypeFlag; + if (i === 0) { + context.InFirstTypeArgument = addInFirstTypeArgumentFlag; + } + const typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); + return result; + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword); const name = getNameFromIndexInfo(indexInfo) || "x"; @@ -2889,9 +2896,8 @@ namespace ts { Debug.assert(chain && 0 <= index && index < chain.length); // const parentIndex = index - 1; const symbol = chain[index]; - let typeParameterString = ""; + let typeParameterNodes: TypeNode[] | undefined; if (index > 0) { - const parentSymbol = chain[index - 1]; let typeParameters: TypeParameter[]; if (getCheckFlags(symbol) & CheckFlags.Instantiated) { @@ -2907,17 +2913,12 @@ namespace ts { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowTypeParameterInQualifiedName)) { context.encounteredError = true; } - const writer = getSingleLineStringWriter(); - const displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - releaseStringWriter(writer); - + typeParameterNodes = typeParameters && mapToTypeNodeArray(typeParameters, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); } } + const symbolName = getNameOfSymbol(symbol, context); - const symbolNameWithTypeParameters = typeParameterString.length > 0 ? `${symbolName}<${typeParameterString}>` : symbolName; - const identifier = createIdentifier(symbolNameWithTypeParameters); + const identifier = createIdentifier(symbolName, typeParameterNodes); return index > 0 ? createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 582bc6ed7ab..b96e87ec55c 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -780,6 +780,7 @@ namespace ts { function emitIdentifier(node: Identifier) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 45b09892bb0..510e4ec03de 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -136,15 +136,22 @@ namespace ts { // Identifiers - export function createIdentifier(text: string): Identifier { + export function createIdentifier(text: string, typeArguments?: TypeNode[]): Identifier { const node = createSynthesizedNode(SyntaxKind.Identifier); node.text = escapeIdentifier(text); node.originalKeywordKind = text ? stringToToken(text) : SyntaxKind.Unknown; node.autoGenerateKind = GeneratedIdentifierKind.None; node.autoGenerateId = 0; + node.typeArguments = asNodeArray(typeArguments); return node; } + export function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + let nextAutoGenerateId = 0; /** Create a unique temporary variable. */ diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 67b73cdbda5..ad89069c286 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -575,6 +575,7 @@ namespace ts { /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace + /*@internal*/ typeArguments: NodeArray; // Only defined on synthesized nodes.Though not syntactically valid, used in emitting diagnostics. } // Transient identifier node (marked by id === -1) diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 1e196a925f8..fce43b622bb 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -219,6 +219,9 @@ namespace ts { } switch (node.kind) { + case SyntaxKind.Identifier: + return updateIdentifier(node, nodesVisitor((node).typeArguments, visitor, isTypeNode)); + case SyntaxKind.SemicolonClassElement: case SyntaxKind.EmptyStatement: case SyntaxKind.OmittedExpression: diff --git a/src/services/services.ts b/src/services/services.ts index 8f2cbb22379..faf27f4f2b0 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -357,6 +357,7 @@ namespace ts { _incrementExpressionBrand: any; _unaryExpressionBrand: any; _expressionBrand: any; + typeArguments: any; constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) { super(pos, end); } From 1bbc94fc67cfbbd7bd5fd76af087362b3aafbdb0 Mon Sep 17 00:00:00 2001 From: Herrington Darkholme Date: Wed, 10 May 2017 12:29:53 +0800 Subject: [PATCH 142/282] fix #15666: mark file as optional in Diagnostic --- src/compiler/types.ts | 6 +++--- tests/baselines/reference/APISample_compile.js | 17 +++++++++++++---- tests/baselines/reference/APISample_watcher.js | 7 ++++--- tests/cases/compiler/APISample_compile.ts | 10 +++++++--- tests/cases/compiler/APISample_watcher.ts | 6 +++--- 5 files changed, 30 insertions(+), 16 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index bbbce158caa..2ca9134fb6c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3355,9 +3355,9 @@ namespace ts { } export interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; diff --git a/tests/baselines/reference/APISample_compile.js b/tests/baselines/reference/APISample_compile.js index c2617b2a6c6..35d49350457 100644 --- a/tests/baselines/reference/APISample_compile.js +++ b/tests/baselines/reference/APISample_compile.js @@ -1,6 +1,6 @@ //// [APISample_compile.ts] /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -18,8 +18,12 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void var allDiagnostics = ts.getPreEmitDiagnostics(program); allDiagnostics.forEach(diagnostic => { - var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (!diagnostic.file) { + console.log(message); + return; + } + var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); }); @@ -31,7 +35,8 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void compile(process.argv.slice(2), { noEmitOnError: true, noImplicitAny: true, target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS -}); +}); + //// [APISample_compile.js] "use strict"; @@ -47,8 +52,12 @@ function compile(fileNames, options) { var emitResult = program.emit(); var allDiagnostics = ts.getPreEmitDiagnostics(program); allDiagnostics.forEach(function (diagnostic) { - var _a = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start), line = _a.line, character = _a.character; var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (!diagnostic.file) { + console.log(message); + return; + } + var _a = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start), line = _a.line, character = _a.character; console.log(diagnostic.file.fileName + " (" + (line + 1) + "," + (character + 1) + "): " + message); }); var exitCode = emitResult.emitSkipped ? 1 : 0; diff --git a/tests/baselines/reference/APISample_watcher.js b/tests/baselines/reference/APISample_watcher.js index f06f9ced73f..b813a44f53e 100644 --- a/tests/baselines/reference/APISample_watcher.js +++ b/tests/baselines/reference/APISample_watcher.js @@ -1,6 +1,6 @@ //// [APISample_watcher.ts] /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -91,7 +91,7 @@ function watch(rootFileNames: string[], options: ts.CompilerOptions) { allDiagnostics.forEach(diagnostic => { let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); if (diagnostic.file) { - let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(` Error ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } else { @@ -106,7 +106,8 @@ const currentDirectoryFiles = fs.readdirSync(process.cwd()). filter(fileName=> fileName.length >= 3 && fileName.substr(fileName.length - 3, 3) === ".ts"); // Start the watcher -watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); +watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); + //// [APISample_watcher.js] "use strict"; diff --git a/tests/cases/compiler/APISample_compile.ts b/tests/cases/compiler/APISample_compile.ts index b60c53685aa..c49d2a7b122 100644 --- a/tests/cases/compiler/APISample_compile.ts +++ b/tests/cases/compiler/APISample_compile.ts @@ -4,7 +4,7 @@ // @strictNullChecks:true /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -22,8 +22,12 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void var allDiagnostics = ts.getPreEmitDiagnostics(program); allDiagnostics.forEach(diagnostic => { - var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (!diagnostic.file) { + console.log(message); + return; + } + var { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); }); @@ -35,4 +39,4 @@ export function compile(fileNames: string[], options: ts.CompilerOptions): void compile(process.argv.slice(2), { noEmitOnError: true, noImplicitAny: true, target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS -}); \ No newline at end of file +}); diff --git a/tests/cases/compiler/APISample_watcher.ts b/tests/cases/compiler/APISample_watcher.ts index 07922bd35c7..3e8ce3d8d63 100644 --- a/tests/cases/compiler/APISample_watcher.ts +++ b/tests/cases/compiler/APISample_watcher.ts @@ -4,7 +4,7 @@ // @strictNullChecks:true /* - * Note: This test is a public API sample. The sample sources can be found + * Note: This test is a public API sample. The sample sources can be found at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services * Please log a "breaking change" issue for any API breaking change affecting this issue */ @@ -95,7 +95,7 @@ function watch(rootFileNames: string[], options: ts.CompilerOptions) { allDiagnostics.forEach(diagnostic => { let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); if (diagnostic.file) { - let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); console.log(` Error ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } else { @@ -110,4 +110,4 @@ const currentDirectoryFiles = fs.readdirSync(process.cwd()). filter(fileName=> fileName.length >= 3 && fileName.substr(fileName.length - 3, 3) === ".ts"); // Start the watcher -watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); \ No newline at end of file +watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS }); From 71fb02c099d40a3a3709eb90f0d897179c7dbca2 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 9 May 2017 12:20:52 -0700 Subject: [PATCH 143/282] Support find-all-references for a module specifier --- src/compiler/program.ts | 81 ++++++++++------- src/compiler/types.ts | 2 + src/compiler/utilities.ts | 16 ++-- src/harness/fourslash.ts | 13 ++- .../unittests/services/preProcessFile.ts | 16 ++-- src/services/documentHighlights.ts | 8 +- src/services/findAllReferences.ts | 90 +++++++++++++++---- src/services/goToDefinition.ts | 2 +- src/services/importTracker.ts | 34 +++++++ src/services/services.ts | 8 +- src/services/utilities.ts | 4 + ...eclarationEmitInvalidReference2.errors.txt | 4 +- .../invalidTripleSlashReference.errors.txt | 8 +- .../reference/library-reference-5.errors.txt | 4 +- .../reference/parserRealSource1.errors.txt | 4 +- .../reference/parserRealSource10.errors.txt | 4 +- .../reference/parserRealSource11.errors.txt | 4 +- .../reference/parserRealSource12.errors.txt | 4 +- .../reference/parserRealSource13.errors.txt | 4 +- .../reference/parserRealSource14.errors.txt | 4 +- .../reference/parserRealSource2.errors.txt | 4 +- .../reference/parserRealSource3.errors.txt | 4 +- .../reference/parserRealSource4.errors.txt | 4 +- .../reference/parserRealSource5.errors.txt | 4 +- .../reference/parserRealSource6.errors.txt | 4 +- .../reference/parserRealSource7.errors.txt | 4 +- .../reference/parserRealSource8.errors.txt | 4 +- .../reference/parserRealSource9.errors.txt | 4 +- .../reference/parserharness.errors.txt | 16 ++-- .../reference/parserindenter.errors.txt | 4 +- ...ibilityOfTypeUsedAcrossModules2.errors.txt | 12 +-- ...ibilityOfTypeUsedAcrossModules2.errors.txt | 12 +-- .../reference/scannertest1.errors.txt | 4 +- .../reference/selfReferencingFile.errors.txt | 4 +- .../reference/selfReferencingFile2.errors.txt | 4 +- .../reference/selfReferencingFile3.errors.txt | 4 +- tests/cases/fourslash/findAllRefsForModule.ts | 23 +++++ .../fourslash/findAllRefsForModuleGlobal.ts | 17 ++++ ...currencesIsDefinitionOfComputedProperty.ts | 2 +- tests/cases/fourslash/getPreProcessedFile.ts | 4 +- tests/cases/fourslash/quickInfoForRequire.ts | 1 - .../cases/fourslash/referencesForAmbients.ts | 4 +- .../referencesForExternalModuleNames.ts | 3 +- .../fourslash/shims-pp/getPreProcessedFile.ts | 4 +- .../fourslash/shims/getPreProcessedFile.ts | 4 +- 45 files changed, 312 insertions(+), 156 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsForModule.ts create mode 100644 tests/cases/fourslash/findAllRefsForModuleGlobal.ts diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 7893fee651e..5c7c99a2410 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -434,7 +434,8 @@ namespace ts { getFileProcessingDiagnostics: () => fileProcessingDiagnostics, getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives, isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference, }; verifyCompilerOptions(); @@ -1348,48 +1349,60 @@ namespace ts { } } - function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { - let diagnosticArgument: string[]; - let diagnostic: DiagnosticMessage; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), fileName => filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName))); + } + + function getSourceFileFromReferenceWorker( + fileName: string, + getSourceFile: (fileName: string) => SourceFile | undefined, + fail?: (diagnostic: DiagnosticMessage, ...argument: string[]) => void, + refFile?: SourceFile): SourceFile | undefined { + if (hasExtension(fileName)) { if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { - diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) fail(Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; - } - } - else { - const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) { - diagnostic = Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } - } - } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument)); + const sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } - else { - fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument)); + return sourceFile; + } else { + const sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) return sourceFileNoExtension; + + if (fail && options.allowNonTsExtensions) { + fail(Diagnostics.File_0_not_found, fileName); + return undefined; } + + const sourceFileWithAddedExtension = forEach(supportedExtensions, extension => getSourceFile(fileName + extension)); + if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): void { + getSourceFileFromReferenceWorker(fileName, + fileName => findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd), + (diagnostic, ...args) => { + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...args) + : createCompilerDiagnostic(diagnostic, ...args)); + }, + refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 74670352c34..4ea1076f072 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2411,6 +2411,8 @@ namespace ts { /* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean; // For testing purposes only. /* @internal */ structureIsReused?: StructureIsReused; + + /* @internal */ getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined; } /* @internal */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 460a9860f1e..7bdbe3a073f 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1918,21 +1918,19 @@ namespace ts { const isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { const refMatchResult = fullTripleSlashReferencePathRegEx.exec(comment); const refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - const start = commentRange.pos; - const end = commentRange.end; + const match = refMatchResult || refLibResult; + if (match) { + const pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 83d27c951be..7626f7d1a87 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -995,8 +995,7 @@ namespace FourSlash { public verifyReferenceGroups(startRanges: Range | Range[], parts: Array<{ definition: string, ranges: Range[] }>): void { interface ReferenceJson { definition: string; ranges: ts.ReferenceEntry[]; } - type ReferencesJson = ReferenceJson[]; - const fullExpected = parts.map(({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) })); + const fullExpected = ts.map(parts, ({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) })); for (const startRange of toArray(startRanges)) { this.goToRangeStart(startRange); @@ -1004,7 +1003,7 @@ namespace FourSlash { definition: definition.displayParts.map(d => d.text).join(""), ranges: references })); - this.assertObjectsEqual(fullActual, fullExpected); + this.assertObjectsEqual(fullActual, fullExpected); } function rangeToReferenceEntry(r: Range): ts.ReferenceEntry { @@ -1062,6 +1061,14 @@ namespace FourSlash { } } }; + if (fullActual === undefined || fullExpected === undefined) { + if (fullActual === fullExpected) { + return; + } + console.log("Expected:", stringify(fullExpected)); + console.log("Actual: ", stringify(fullActual)); + this.raiseError(msgPrefix); + } recur(fullActual, fullExpected, ""); } diff --git a/src/harness/unittests/services/preProcessFile.ts b/src/harness/unittests/services/preProcessFile.ts index 65f68b8ca25..6e77c27e4a8 100644 --- a/src/harness/unittests/services/preProcessFile.ts +++ b/src/harness/unittests/services/preProcessFile.ts @@ -37,8 +37,8 @@ describe("PreProcessFile:", function () { /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { - referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 37 }, { fileName: "refFile2.ts", pos: 38, end: 73 }, - { fileName: "refFile3.ts", pos: 74, end: 109 }, { fileName: "..\\refFile4d.ts", pos: 110, end: 150 }], + referencedFiles: [{ fileName: "refFile1.ts", pos: 22, end: 33 }, { fileName: "refFile2.ts", pos: 59, end: 70 }, + { fileName: "refFile3.ts", pos: 94, end: 105 }, { fileName: "..\\refFile4d.ts", pos: 131, end: 146 }], importedFiles: [], typeReferenceDirectives: [], ambientExternalModules: undefined, @@ -104,7 +104,7 @@ describe("PreProcessFile:", function () { /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { - referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }, { fileName: "refFile2.ts", pos: 36, end: 71 }], + referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }, { fileName: "refFile2.ts", pos: 57, end: 68 }], typeReferenceDirectives: [], importedFiles: [{ fileName: "r1.ts", pos: 92, end: 97 }, { fileName: "r2.ts", pos: 121, end: 126 }], ambientExternalModules: undefined, @@ -117,7 +117,7 @@ describe("PreProcessFile:", function () { /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { - referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }], + referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }], typeReferenceDirectives: [], importedFiles: [{ fileName: "r1.ts", pos: 91, end: 96 }, { fileName: "r3.ts", pos: 148, end: 153 }], ambientExternalModules: undefined, @@ -442,12 +442,12 @@ describe("PreProcessFile:", function () { /*detectJavaScriptImports*/ false, { referencedFiles: [ - { "pos": 13, "end": 38, "fileName": "a" }, - { "pos": 91, "end": 117, "fileName": "a2" } + { "pos": 34, "end": 35, "fileName": "a" }, + { "pos": 112, "end": 114, "fileName": "a2" } ], typeReferenceDirectives: [ - { "pos": 51, "end": 78, "fileName": "a1" }, - { "pos": 130, "end": 157, "fileName": "a3" } + { "pos": 73, "end": 75, "fileName": "a1" }, + { "pos": 152, "end": 154, "fileName": "a3" } ], importedFiles: [], ambientExternalModules: undefined, diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index a8afc46d736..f5e565d4a9e 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -1,8 +1,8 @@ /* @internal */ namespace ts.DocumentHighlights { - export function getDocumentHighlights(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { + export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { const node = getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } function getHighlightSpanForNode(node: Node, sourceFile: SourceFile): HighlightSpan { @@ -16,8 +16,8 @@ namespace ts.DocumentHighlights { }; } - function getSemanticDocumentHighlights(node: Node, typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { - const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { + const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 7be2229877a..92ca47cbed6 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -41,14 +41,15 @@ namespace ts.FindAllReferences { readonly implementations?: boolean; } - export function findReferencedSymbols(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { - const referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { + const referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } const out: ReferencedSymbol[] = []; + const checker = program.getTypeChecker(); for (const { definition, references } of referencedSymbols) { // Only include referenced symbols that have a valid definition. if (definition) { @@ -59,44 +60,46 @@ namespace ts.FindAllReferences { return out; } - export function getImplementationsAtPosition(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] { + export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] { const node = getTouchingPropertyName(sourceFile, position); - const referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + const checker = program.getTypeChecker(); return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } - function getImplementationReferenceEntries(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined { + function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined { + const checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { const result: NodeEntry[] = []; - Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, node => result.push(nodeEntry(node))); + Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, node => result.push(nodeEntry(node))); return result; } else if (node.kind === SyntaxKind.SuperKeyword || isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - const symbol = typeChecker.getSymbolAtLocation(node); + const symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - export function findReferencedEntries(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined { - const x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + export function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined { + const x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return map(x, toReferenceEntry); } - export function getReferenceEntriesForNode(node: Node, sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined { - return flattenEntries(Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + export function getReferenceEntriesForNode(node: Node, program: Program, sourceFiles: SourceFile[], cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined { + return flattenEntries(Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } - function findAllReferencedSymbols(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined { + function findAllReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined { const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols: SymbolAndEntries[]): Entry[] { @@ -257,7 +260,7 @@ namespace ts.FindAllReferences { /* @internal */ namespace ts.FindAllReferences.Core { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - export function getReferencedSymbolsForNode(node: Node, sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined { + export function getReferencedSymbolsForNode(node: Node, program: Program, sourceFiles: SourceFile[], cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined { if (node.kind === ts.SyntaxKind.SourceFile) { return undefined; } @@ -269,6 +272,7 @@ namespace ts.FindAllReferences.Core { } } + const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier @@ -281,9 +285,65 @@ namespace ts.FindAllReferences.Core { return undefined; } + if (symbol.flags & SymbolFlags.Module && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); + } + return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } + function isModuleReferenceLocation(node: ts.Node): boolean { + if (node.kind !== SyntaxKind.StringLiteral) { + return false; + } + switch (node.parent.kind) { + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.ExternalModuleReference: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + return true; + case SyntaxKind.CallExpression: + return isRequireCall(node.parent as CallExpression, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + + function getReferencedSymbolsForModule(program: Program, symbol: Symbol, sourceFiles: SourceFile[]): SymbolAndEntries[] { + Debug.assert(!!symbol.valueDeclaration); + + const references = findModuleReferences(program, sourceFiles, symbol).map(reference => { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: createTextSpanFromRange(reference.ref), + }; + } + }); + + for (const decl of symbol.declarations) { + switch (decl.kind) { + case ts.SyntaxKind.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 ts.SyntaxKind.ModuleDeclaration: + references.push({ type: "node", node: (decl as ts.ModuleDeclaration).name }); + break; + default: + Debug.assert(false); + } + } + + return [{ + definition: { type: "symbol", symbol, node: symbol.valueDeclaration }, + references + }]; + } + /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node: Node, sourceFiles: SourceFile[], cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { if (isTypeKeyword(node.kind)) { diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 09d1f2a248c..52ffb42dbde 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -266,7 +266,7 @@ namespace ts.GoToDefinition { function findReferenceInPosition(refs: FileReference[], pos: number): FileReference { for (const ref of refs) { - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index df50f3ec31c..e8528b366b9 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -300,6 +300,40 @@ namespace ts.FindAllReferences { }); } + type ModuleReference = + /** "import" also includes require() calls. */ + | { kind: "import", literal: StringLiteral } + /** or */ + | { kind: "reference", referencingFile: SourceFile, ref: FileReference }; + export function findModuleReferences(program: Program, sourceFiles: SourceFile[], searchModuleSymbol: Symbol): ModuleReference[] { + const refs: ModuleReference[] = []; + const checker = program.getTypeChecker(); + for (const referencingFile of sourceFiles) { + const searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === ts.SyntaxKind.SourceFile) { + for (const ref of referencingFile.referencedFiles) { + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile, ref }); + } + } + for (const ref of referencingFile.typeReferenceDirectives) { + const referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === (searchSourceFile as ts.SourceFile).fileName) { + refs.push({ kind: "reference", referencingFile, ref }); + } + } + } + + forEachImport(referencingFile, (_importDecl, moduleSpecifier) => { + const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken): Map { const map = createMap(); diff --git a/src/services/services.ts b/src/services/services.ts index 1b4678b5dbc..4703a27570d 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1416,7 +1416,7 @@ namespace ts { /// Goto implementation function getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] { synchronizeHostData(); - return FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences @@ -1438,7 +1438,7 @@ namespace ts { synchronizeHostData(); const sourceFilesToSearch = map(filesToSearch, f => program.getSourceFile(f)); const sourceFile = getValidSourceFile(fileName); - return DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName: string, position: number): ReferenceEntry[] { @@ -1476,12 +1476,12 @@ namespace ts { function getReferences(fileName: string, position: number, options?: FindAllReferences.Options) { synchronizeHostData(); - return FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName: string, position: number): ReferencedSymbol[] { synchronizeHostData(); - return FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 065c42245f6..405834fc3be 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1112,6 +1112,10 @@ namespace ts { return createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } + export function createTextSpanFromRange(range: TextRange): TextSpan { + return createTextSpanFromBounds(range.pos, range.end); + } + export function isTypeKeyword(kind: SyntaxKind): boolean { switch (kind) { case SyntaxKind.AnyKeyword: diff --git a/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt b/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt index 32423b8d849..cca1805ea35 100644 --- a/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt +++ b/tests/baselines/reference/declarationEmitInvalidReference2.errors.txt @@ -1,8 +1,8 @@ -tests/cases/compiler/declarationEmitInvalidReference2.ts(1,1): error TS6053: File 'tests/cases/compiler/invalid.ts' not found. +tests/cases/compiler/declarationEmitInvalidReference2.ts(1,22): error TS6053: File 'tests/cases/compiler/invalid.ts' not found. ==== tests/cases/compiler/declarationEmitInvalidReference2.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~ !!! error TS6053: File 'tests/cases/compiler/invalid.ts' not found. var x = 0; \ No newline at end of file diff --git a/tests/baselines/reference/invalidTripleSlashReference.errors.txt b/tests/baselines/reference/invalidTripleSlashReference.errors.txt index 1de5ecaaae1..8fef26aa5aa 100644 --- a/tests/baselines/reference/invalidTripleSlashReference.errors.txt +++ b/tests/baselines/reference/invalidTripleSlashReference.errors.txt @@ -1,13 +1,13 @@ -tests/cases/compiler/invalidTripleSlashReference.ts(1,1): error TS6053: File 'tests/cases/compiler/filedoesnotexist.ts' not found. -tests/cases/compiler/invalidTripleSlashReference.ts(2,1): error TS6053: File 'tests/cases/compiler/otherdoesnotexist.d.ts' not found. +tests/cases/compiler/invalidTripleSlashReference.ts(1,22): error TS6053: File 'tests/cases/compiler/filedoesnotexist.ts' not found. +tests/cases/compiler/invalidTripleSlashReference.ts(2,22): error TS6053: File 'tests/cases/compiler/otherdoesnotexist.d.ts' not found. ==== tests/cases/compiler/invalidTripleSlashReference.ts (2 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/compiler/filedoesnotexist.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/compiler/otherdoesnotexist.d.ts' not found. // this test doesn't actually give the errors you want due to the way the compiler reports errors diff --git a/tests/baselines/reference/library-reference-5.errors.txt b/tests/baselines/reference/library-reference-5.errors.txt index 2130b1ce037..173865ed82d 100644 --- a/tests/baselines/reference/library-reference-5.errors.txt +++ b/tests/baselines/reference/library-reference-5.errors.txt @@ -1,4 +1,4 @@ -/node_modules/bar/index.d.ts(1,1): message TS4090: Conflicting definitions for 'alpha' found at '/node_modules/bar/node_modules/alpha/index.d.ts' and '/node_modules/foo/node_modules/alpha/index.d.ts'. Consider installing a specific version of this library to resolve the conflict. +/node_modules/bar/index.d.ts(1,23): message TS4090: Conflicting definitions for 'alpha' found at '/node_modules/bar/node_modules/alpha/index.d.ts' and '/node_modules/foo/node_modules/alpha/index.d.ts'. Consider installing a specific version of this library to resolve the conflict. ==== /src/root.ts (0 errors) ==== @@ -16,7 +16,7 @@ ==== /node_modules/bar/index.d.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~ !!! message TS4090: Conflicting definitions for 'alpha' found at '/node_modules/bar/node_modules/alpha/index.d.ts' and '/node_modules/foo/node_modules/alpha/index.d.ts'. Consider installing a specific version of this library to resolve the conflict. declare var bar: any; diff --git a/tests/baselines/reference/parserRealSource1.errors.txt b/tests/baselines/reference/parserRealSource1.errors.txt index 23d1a1d744a..696eff552a1 100644 --- a/tests/baselines/reference/parserRealSource1.errors.txt +++ b/tests/baselines/reference/parserRealSource1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. ==== tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts (1 errors) ==== @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource1.ts(4,1): error TS60 // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource10.errors.txt b/tests/baselines/reference/parserRealSource10.errors.txt index 7d65c1690fe..6fd27b8351e 100644 --- a/tests/baselines/reference/parserRealSource10.errors.txt +++ b/tests/baselines/reference/parserRealSource10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,33): error TS2449: Class 'TokenInfo' used before its declaration. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(127,42): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(128,36): error TS2693: 'string' only refers to a type, but is being used as a value here. @@ -348,7 +348,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource10.ts(449,40): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource11.errors.txt b/tests/baselines/reference/parserRealSource11.errors.txt index ba52fa5b62d..26cb07614a5 100644 --- a/tests/baselines/reference/parserRealSource11.errors.txt +++ b/tests/baselines/reference/parserRealSource11.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(13,22): error TS2304: Cannot find name 'Type'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(14,24): error TS2304: Cannot find name 'ASTFlags'. tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(17,38): error TS2304: Cannot find name 'CompilerDiagnostics'. @@ -522,7 +522,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource11.ts(2356,48): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource12.errors.txt b/tests/baselines/reference/parserRealSource12.errors.txt index 22fb209d80c..a1e959d38cc 100644 --- a/tests/baselines/reference/parserRealSource12.errors.txt +++ b/tests/baselines/reference/parserRealSource12.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(8,19): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(8,32): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(8,38): error TS2304: Cannot find name 'AST'. @@ -214,7 +214,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource12.ts(524,30): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource13.errors.txt b/tests/baselines/reference/parserRealSource13.errors.txt index ddf67bb6dad..35bdd1cbb62 100644 --- a/tests/baselines/reference/parserRealSource13.errors.txt +++ b/tests/baselines/reference/parserRealSource13.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(8,35): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(9,39): error TS2304: Cannot find name 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(10,34): error TS2304: Cannot find name 'AST'. @@ -121,7 +121,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource13.ts(135,36): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript.AstWalkerWithDetailCallback { diff --git a/tests/baselines/reference/parserRealSource14.errors.txt b/tests/baselines/reference/parserRealSource14.errors.txt index 8682b1e6557..2e1fe6e7b56 100644 --- a/tests/baselines/reference/parserRealSource14.errors.txt +++ b/tests/baselines/reference/parserRealSource14.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(24,33): error TS2694: Namespace 'TypeScript' has no exported member 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(38,34): error TS2694: Namespace 'TypeScript' has no exported member 'AST'. tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(48,37): error TS2694: Namespace 'TypeScript' has no exported member 'AST'. @@ -165,7 +165,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource14.ts(572,20): error // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource2.errors.txt b/tests/baselines/reference/parserRealSource2.errors.txt index 42fcff36c70..8e0e1f13b15 100644 --- a/tests/baselines/reference/parserRealSource2.errors.txt +++ b/tests/baselines/reference/parserRealSource2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. ==== tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts (1 errors) ==== @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource2.ts(4,1): error TS60 // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource3.errors.txt b/tests/baselines/reference/parserRealSource3.errors.txt index 5b00994052b..1ee68afa81a 100644 --- a/tests/baselines/reference/parserRealSource3.errors.txt +++ b/tests/baselines/reference/parserRealSource3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. ==== tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts (1 errors) ==== @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource3.ts(4,1): error TS60 // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource4.errors.txt b/tests/baselines/reference/parserRealSource4.errors.txt index 9722a5b670d..5fe47b7a8e3 100644 --- a/tests/baselines/reference/parserRealSource4.errors.txt +++ b/tests/baselines/reference/parserRealSource4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(195,37): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array()' instead. @@ -7,7 +7,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource4.ts(195,37): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource5.errors.txt b/tests/baselines/reference/parserRealSource5.errors.txt index 7dc9b5942d5..fd2932df0d9 100644 --- a/tests/baselines/reference/parserRealSource5.errors.txt +++ b/tests/baselines/reference/parserRealSource5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(14,38): error TS2304: Cannot find name 'ITextWriter'. tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(14,66): error TS2304: Cannot find name 'Parser'. tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(27,17): error TS2304: Cannot find name 'CompilerDiagnostics'. @@ -15,7 +15,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource5.ts(61,65): error TS // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource6.errors.txt b/tests/baselines/reference/parserRealSource6.errors.txt index aa6a9f41392..75c0ae8c139 100644 --- a/tests/baselines/reference/parserRealSource6.errors.txt +++ b/tests/baselines/reference/parserRealSource6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(8,24): error TS2304: Cannot find name 'Script'. tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(10,41): error TS2304: Cannot find name 'ScopeChain'. tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(10,69): error TS2304: Cannot find name 'TypeChecker'. @@ -66,7 +66,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource6.ts(215,20): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource7.errors.txt b/tests/baselines/reference/parserRealSource7.errors.txt index 1261d7b5f06..f98dd31dba9 100644 --- a/tests/baselines/reference/parserRealSource7.errors.txt +++ b/tests/baselines/reference/parserRealSource7.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(12,38): error TS2304: Cannot find name 'ASTList'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(12,62): error TS2304: Cannot find name 'TypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(16,37): error TS2552: Cannot find name 'TypeLink'. Did you mean 'typeLink'? @@ -308,7 +308,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource7.ts(828,13): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource8.errors.txt b/tests/baselines/reference/parserRealSource8.errors.txt index 4fbf039ae0a..a7a2b968baf 100644 --- a/tests/baselines/reference/parserRealSource8.errors.txt +++ b/tests/baselines/reference/parserRealSource8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(9,41): error TS2304: Cannot find name 'ScopeChain'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(10,39): error TS2304: Cannot find name 'TypeFlow'. tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(11,43): error TS2304: Cannot find name 'ModuleDeclaration'. @@ -139,7 +139,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts(454,35): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserRealSource9.errors.txt b/tests/baselines/reference/parserRealSource9.errors.txt index caa142db60e..6533fdbcfc4 100644 --- a/tests/baselines/reference/parserRealSource9.errors.txt +++ b/tests/baselines/reference/parserRealSource9.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(4,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(4,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(8,38): error TS2304: Cannot find name 'TypeChecker'. tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(9,48): error TS2304: Cannot find name 'TypeLink'. tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(9,67): error TS2304: Cannot find name 'SymbolScope'. @@ -38,7 +38,7 @@ tests/cases/conformance/parser/ecmascript5/parserRealSource9.ts(200,48): error T // See LICENSE.txt in the project root for complete license information. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/typescript.ts' not found. module TypeScript { diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index d4aa6682c40..e7c83f0a058 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(16,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/io.ts' not found. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(17,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/typescript.ts' not found. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(18,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/services/typescriptServices.ts' not found. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(19,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/diff.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(16,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/io.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(17,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/typescript.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(18,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/services/typescriptServices.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(19,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/diff.ts' not found. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(21,29): error TS2694: Namespace 'Harness' has no exported member 'Assert'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(25,17): error TS2304: Cannot find name 'IIO'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(41,12): error TS2304: Cannot find name 'ActiveXObject'. @@ -127,16 +127,16 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): // /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/io.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/compiler/typescript.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/services/typescriptServices.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/diff.ts' not found. declare var assert: Harness.Assert; diff --git a/tests/baselines/reference/parserindenter.errors.txt b/tests/baselines/reference/parserindenter.errors.txt index 2f51281e7aa..371072a4622 100644 --- a/tests/baselines/reference/parserindenter.errors.txt +++ b/tests/baselines/reference/parserindenter.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(16,1): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/formatting.ts' not found. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(16,21): error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/formatting.ts' not found. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(20,38): error TS2304: Cannot find name 'ILineIndenationResolver'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(22,33): error TS2304: Cannot find name 'IndentationBag'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(24,42): error TS2304: Cannot find name 'Dictionary_int_int'. @@ -145,7 +145,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): // /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/parser/ecmascript5/RealWorld/formatting.ts' not found. diff --git a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt index d5c992fff66..88f77a6a2e8 100644 --- a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt +++ b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/amd/visibilityOfTypeUsedAcrossModules2.errors.txt @@ -1,15 +1,15 @@ -main.ts(1,1): error TS1006: A file cannot have a reference to itself. -main.ts(2,1): error TS6053: File 'nonExistingFile1.ts' not found. -main.ts(3,1): error TS6053: File 'nonExistingFile2.ts' not found. +main.ts(1,22): error TS1006: A file cannot have a reference to itself. +main.ts(2,22): error TS6053: File 'nonExistingFile1.ts' not found. +main.ts(3,22): error TS6053: File 'nonExistingFile2.ts' not found. ==== main.ts (3 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile1.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile2.ts' not found. \ No newline at end of file diff --git a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt index d5c992fff66..88f77a6a2e8 100644 --- a/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt +++ b/tests/baselines/reference/project/visibilityOfTypeUsedAcrossModules2/node/visibilityOfTypeUsedAcrossModules2.errors.txt @@ -1,15 +1,15 @@ -main.ts(1,1): error TS1006: A file cannot have a reference to itself. -main.ts(2,1): error TS6053: File 'nonExistingFile1.ts' not found. -main.ts(3,1): error TS6053: File 'nonExistingFile2.ts' not found. +main.ts(1,22): error TS1006: A file cannot have a reference to itself. +main.ts(2,22): error TS6053: File 'nonExistingFile1.ts' not found. +main.ts(3,22): error TS6053: File 'nonExistingFile2.ts' not found. ==== main.ts (3 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile1.ts' not found. /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'nonExistingFile2.ts' not found. \ No newline at end of file diff --git a/tests/baselines/reference/scannertest1.errors.txt b/tests/baselines/reference/scannertest1.errors.txt index fce2a0b292a..e4059e3881a 100644 --- a/tests/baselines/reference/scannertest1.errors.txt +++ b/tests/baselines/reference/scannertest1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(1,1): error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. +tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(1,21): error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,21): error TS2304: Cannot find name 'CharacterCodes'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(5,47): error TS2304: Cannot find name 'CharacterCodes'. tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(9,16): error TS2662: Cannot find name 'isDecimalDigit'. Did you mean the static member 'CharacterInfo.isDecimalDigit'? @@ -18,7 +18,7 @@ tests/cases/conformance/scanner/ecmascript5/scannertest1.ts(20,23): error TS2304 ==== tests/cases/conformance/scanner/ecmascript5/scannertest1.ts (16 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/conformance/scanner/ecmascript5/References.ts' not found. class CharacterInfo { diff --git a/tests/baselines/reference/selfReferencingFile.errors.txt b/tests/baselines/reference/selfReferencingFile.errors.txt index 8bf68fde774..eddaff4c28d 100644 --- a/tests/baselines/reference/selfReferencingFile.errors.txt +++ b/tests/baselines/reference/selfReferencingFile.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/selfReferencingFile.ts(1,1): error TS1006: A file cannot have a reference to itself. +tests/cases/compiler/selfReferencingFile.ts(1,21): error TS1006: A file cannot have a reference to itself. ==== tests/cases/compiler/selfReferencingFile.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. class selfReferencingFile { diff --git a/tests/baselines/reference/selfReferencingFile2.errors.txt b/tests/baselines/reference/selfReferencingFile2.errors.txt index 002e087d60e..109a5554ffe 100644 --- a/tests/baselines/reference/selfReferencingFile2.errors.txt +++ b/tests/baselines/reference/selfReferencingFile2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/selfReferencingFile2.ts(1,1): error TS6053: File 'tests/cases/selfReferencingFile2.ts' not found. +tests/cases/compiler/selfReferencingFile2.ts(1,21): error TS6053: File 'tests/cases/selfReferencingFile2.ts' not found. ==== tests/cases/compiler/selfReferencingFile2.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS6053: File 'tests/cases/selfReferencingFile2.ts' not found. class selfReferencingFile2 { diff --git a/tests/baselines/reference/selfReferencingFile3.errors.txt b/tests/baselines/reference/selfReferencingFile3.errors.txt index 05cf04ddc4b..b828ba02d7d 100644 --- a/tests/baselines/reference/selfReferencingFile3.errors.txt +++ b/tests/baselines/reference/selfReferencingFile3.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/selfReferencingFile3.ts(1,1): error TS1006: A file cannot have a reference to itself. +tests/cases/compiler/selfReferencingFile3.ts(1,21): error TS1006: A file cannot have a reference to itself. ==== tests/cases/compiler/selfReferencingFile3.ts (1 errors) ==== /// - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS1006: A file cannot have a reference to itself. class selfReferencingFile3 { diff --git a/tests/cases/fourslash/findAllRefsForModule.ts b/tests/cases/fourslash/findAllRefsForModule.ts new file mode 100644 index 00000000000..ae6b216463f --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForModule.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true + +// @Filename: /a.ts +////export const x = 0; + +// @Filename: /b.ts +////import { x } from "[|./a|]"; + +// @Filename: /c/sub.js +////const a = require("[|../a|]"); + +// @Filename: /d.ts +//// /// + +verify.noErrors(); + +const ranges = test.ranges(); +const [r0, r1, r2] = ranges; +verify.referenceGroups([r0, r1], [{ definition: 'module "/a"', ranges: [r0, r2, r1] }]); +// TODO:GH#15736 +verify.referenceGroups(r2, undefined); diff --git a/tests/cases/fourslash/findAllRefsForModuleGlobal.ts b/tests/cases/fourslash/findAllRefsForModuleGlobal.ts new file mode 100644 index 00000000000..25c23faeae5 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForModuleGlobal.ts @@ -0,0 +1,17 @@ +/// + +// @Filename: /node_modules/foo/index.d.ts +////export const x = 0; + +// @Filename: /b.ts +/////// +////import { x } from "[|foo|]"; +////declare module "[|{| "isDefinition": true |}foo|]" {} + +verify.noErrors(); + +const ranges = test.ranges(); +const [r0, r1, r2] = ranges; +verify.referenceGroups([r1, r2], [{ definition: 'module "/node_modules/foo/index"', ranges: [r0, r1, r2] }]); +// TODO:GH#15736 +verify.referenceGroups(r0, undefined); diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts index 27c34e56600..7d6cb0a48af 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts @@ -6,4 +6,4 @@ const ranges = test.ranges(); const [r0, r1, r2] = ranges; verify.referenceGroups(r0, [{ definition: '(property) ["foo"]: number', ranges }]); -verify.referenceGroups([r1, r2], []); // TODO: fix +verify.referenceGroups([r1, r2], undefined); // TODO: fix diff --git a/tests/cases/fourslash/getPreProcessedFile.ts b/tests/cases/fourslash/getPreProcessedFile.ts index 03ce481c8ba..a33a6c9a470 100644 --- a/tests/cases/fourslash/getPreProcessedFile.ts +++ b/tests/cases/fourslash/getPreProcessedFile.ts @@ -5,12 +5,12 @@ //// class D { } // @Filename: refFile2.ts -//// export class E {} +//// export class E {} // @Filename: main.ts // @ResolveReference: true //// /// -//// /*1*/////*2*/ +//// /// //// /*3*/////*4*/ //// import ref2 = require("refFile2"); //// import noExistref2 = require(/*5*/"NotExistRefFile2"/*6*/); diff --git a/tests/cases/fourslash/quickInfoForRequire.ts b/tests/cases/fourslash/quickInfoForRequire.ts index e97810401f4..fe923945429 100644 --- a/tests/cases/fourslash/quickInfoForRequire.ts +++ b/tests/cases/fourslash/quickInfoForRequire.ts @@ -8,4 +8,3 @@ goTo.marker("1"); verify.quickInfoIs("module a"); -verify.noReferences(); diff --git a/tests/cases/fourslash/referencesForAmbients.ts b/tests/cases/fourslash/referencesForAmbients.ts index 58e4d6e59a5..f5789716155 100644 --- a/tests/cases/fourslash/referencesForAmbients.ts +++ b/tests/cases/fourslash/referencesForAmbients.ts @@ -15,7 +15,7 @@ ////} const [moduleFoo0, f0, moduleBar0, foo0, moduleFoo1, foo1, f1, moduleBar1, foo2] = test.ranges(); -verify.singleReferenceGroup('module "foo"', [moduleFoo0, moduleFoo1]); -verify.singleReferenceGroup('module "bar"', [moduleBar0, moduleBar1]); +verify.singleReferenceGroup('module "foo"', [moduleFoo1, moduleFoo0]); +verify.singleReferenceGroup('module "bar"', [moduleBar1, moduleBar0]); verify.singleReferenceGroup('import foo = require("foo")', [foo0, foo1, foo2]); verify.singleReferenceGroup("var f: number", [f0, f1]); diff --git a/tests/cases/fourslash/referencesForExternalModuleNames.ts b/tests/cases/fourslash/referencesForExternalModuleNames.ts index 5e01eae3530..75ea9e908cf 100644 --- a/tests/cases/fourslash/referencesForExternalModuleNames.ts +++ b/tests/cases/fourslash/referencesForExternalModuleNames.ts @@ -13,5 +13,4 @@ const ranges = test.ranges(); const [r0, r1] = ranges; -verify.referenceGroups(r0, [{ definition: 'module "foo"', ranges }]); -verify.referenceGroups(r1, [{ definition: 'module f', ranges }]); +verify.referenceGroups(ranges, [{ definition: 'module "foo"', ranges: [r1, r0] }]); diff --git a/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts b/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts index 03ce481c8ba..a33a6c9a470 100644 --- a/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts +++ b/tests/cases/fourslash/shims-pp/getPreProcessedFile.ts @@ -5,12 +5,12 @@ //// class D { } // @Filename: refFile2.ts -//// export class E {} +//// export class E {} // @Filename: main.ts // @ResolveReference: true //// /// -//// /*1*/////*2*/ +//// /// //// /*3*/////*4*/ //// import ref2 = require("refFile2"); //// import noExistref2 = require(/*5*/"NotExistRefFile2"/*6*/); diff --git a/tests/cases/fourslash/shims/getPreProcessedFile.ts b/tests/cases/fourslash/shims/getPreProcessedFile.ts index 03ce481c8ba..a33a6c9a470 100644 --- a/tests/cases/fourslash/shims/getPreProcessedFile.ts +++ b/tests/cases/fourslash/shims/getPreProcessedFile.ts @@ -5,12 +5,12 @@ //// class D { } // @Filename: refFile2.ts -//// export class E {} +//// export class E {} // @Filename: main.ts // @ResolveReference: true //// /// -//// /*1*/////*2*/ +//// /// //// /*3*/////*4*/ //// import ref2 = require("refFile2"); //// import noExistref2 = require(/*5*/"NotExistRefFile2"/*6*/); From 5a19e30c27f354600d9b273adb702c5eda503886 Mon Sep 17 00:00:00 2001 From: Jason Ramsay Date: Wed, 10 May 2017 11:38:10 -0700 Subject: [PATCH 144/282] In shims.ts resolveModuleName should only return resolved modules found in ts files (.ts, .d.ts, .tsx) --- src/services/shims.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/services/shims.ts b/src/services/shims.ts index 29e24568460..498c1834a60 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -1038,7 +1038,11 @@ namespace ts { return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => { const compilerOptions = JSON.parse(compilerOptionsJson); const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); - const resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== Extension.Ts && result.resolvedModule.extension !== Extension.Tsx && result.resolvedModule.extension !== Extension.Dts) { + resolvedFileName = undefined; + } + return { resolvedFileName, failedLookupLocations: result.failedLookupLocations From 4b4cff5684bcd4b15c6ec21ec30cad4c0b67b359 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 10 May 2017 11:45:01 -0700 Subject: [PATCH 145/282] Correctly emit expression in extends in namespace Shouldn't have a declare for the emitted temp --- src/compiler/declarationEmitter.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 0c1c0acd474..427f1bbd26e 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -67,7 +67,7 @@ namespace ts { let errorNameNode: DeclarationName; const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments; const emit = compilerOptions.stripInternal ? stripInternal : emitNode; - let noDeclare: boolean; + let needsDeclare: boolean = true; let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; @@ -110,11 +110,11 @@ namespace ts { resultHasExternalModuleIndicator = false; if (!isBundledEmit || !isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write(`declare module "${getResolvedExternalModuleName(host, sourceFile)}" {`); writeLine(); increaseIndent(); @@ -612,9 +612,9 @@ namespace ts { } } - function emitTempVariableDeclaration(expr: Expression, baseName: string, diagnostic: SymbolAccessibilityDiagnostic): string { + function emitTempVariableDeclaration(expr: Expression, baseName: string, diagnostic: SymbolAccessibilityDiagnostic, needsDeclare: boolean): string { const tempVarName = getExportTempVariableName(baseName); - if (!noDeclare) { + if (needsDeclare) { write("declare "); } write("const "); @@ -636,7 +636,7 @@ namespace ts { const tempVarName = emitTempVariableDeclaration(node.expression, "_default", { diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node - }); + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -728,7 +728,7 @@ namespace ts { if (modifiers & ModifierFlags.Default) { write("default "); } - else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) { + else if (node.kind !== SyntaxKind.InterfaceDeclaration && needsDeclare) { write("declare "); } } @@ -1155,7 +1155,7 @@ namespace ts { diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name - }); + }, !findAncestor(node, n => n.kind === SyntaxKind.ModuleDeclaration)); } emitJsDocComments(node); From cf2c88c398fdb8f74bb6a85e531a5cefd49e378a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 10 May 2017 11:48:32 -0700 Subject: [PATCH 146/282] Test: no declare in declaration tmp in namespace --- .../declarationEmitExpressionInExtends5.js | 67 +++++++++++++++++++ ...eclarationEmitExpressionInExtends5.symbols | 33 +++++++++ .../declarationEmitExpressionInExtends5.types | 35 ++++++++++ .../declarationEmitExpressionInExtends5.ts | 20 ++++++ 4 files changed, 155 insertions(+) create mode 100644 tests/baselines/reference/declarationEmitExpressionInExtends5.js create mode 100644 tests/baselines/reference/declarationEmitExpressionInExtends5.symbols create mode 100644 tests/baselines/reference/declarationEmitExpressionInExtends5.types create mode 100644 tests/cases/compiler/declarationEmitExpressionInExtends5.ts diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends5.js b/tests/baselines/reference/declarationEmitExpressionInExtends5.js new file mode 100644 index 00000000000..77f8fc0e12c --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpressionInExtends5.js @@ -0,0 +1,67 @@ +//// [declarationEmitExpressionInExtends5.ts] +namespace Test +{ + export interface IFace + { + } + + export class SomeClass implements IFace + { + } + + export class Derived extends getClass() + { + } + + export function getClass() : new() => T + { + return SomeClass as (new() => T); + } +} + + +//// [declarationEmitExpressionInExtends5.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var Test; +(function (Test) { + var SomeClass = (function () { + function SomeClass() { + } + return SomeClass; + }()); + Test.SomeClass = SomeClass; + var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Derived; + }(getClass())); + Test.Derived = Derived; + function getClass() { + return SomeClass; + } + Test.getClass = getClass; +})(Test || (Test = {})); + + +//// [declarationEmitExpressionInExtends5.d.ts] +declare namespace Test { + interface IFace { + } + class SomeClass implements IFace { + } + const Derived_base: new () => IFace; + class Derived extends Derived_base { + } + function getClass(): new () => T; +} diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends5.symbols b/tests/baselines/reference/declarationEmitExpressionInExtends5.symbols new file mode 100644 index 00000000000..42bf5892211 --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpressionInExtends5.symbols @@ -0,0 +1,33 @@ +=== tests/cases/compiler/declarationEmitExpressionInExtends5.ts === +namespace Test +>Test : Symbol(Test, Decl(declarationEmitExpressionInExtends5.ts, 0, 0)) +{ + export interface IFace +>IFace : Symbol(IFace, Decl(declarationEmitExpressionInExtends5.ts, 1, 1)) + { + } + + export class SomeClass implements IFace +>SomeClass : Symbol(SomeClass, Decl(declarationEmitExpressionInExtends5.ts, 4, 2)) +>IFace : Symbol(IFace, Decl(declarationEmitExpressionInExtends5.ts, 1, 1)) + { + } + + export class Derived extends getClass() +>Derived : Symbol(Derived, Decl(declarationEmitExpressionInExtends5.ts, 8, 2)) +>getClass : Symbol(getClass, Decl(declarationEmitExpressionInExtends5.ts, 12, 2)) +>IFace : Symbol(IFace, Decl(declarationEmitExpressionInExtends5.ts, 1, 1)) + { + } + + export function getClass() : new() => T +>getClass : Symbol(getClass, Decl(declarationEmitExpressionInExtends5.ts, 12, 2)) +>T : Symbol(T, Decl(declarationEmitExpressionInExtends5.ts, 14, 26)) +>T : Symbol(T, Decl(declarationEmitExpressionInExtends5.ts, 14, 26)) + { + return SomeClass as (new() => T); +>SomeClass : Symbol(SomeClass, Decl(declarationEmitExpressionInExtends5.ts, 4, 2)) +>T : Symbol(T, Decl(declarationEmitExpressionInExtends5.ts, 14, 26)) + } +} + diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends5.types b/tests/baselines/reference/declarationEmitExpressionInExtends5.types new file mode 100644 index 00000000000..22aafb85e58 --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpressionInExtends5.types @@ -0,0 +1,35 @@ +=== tests/cases/compiler/declarationEmitExpressionInExtends5.ts === +namespace Test +>Test : typeof Test +{ + export interface IFace +>IFace : IFace + { + } + + export class SomeClass implements IFace +>SomeClass : SomeClass +>IFace : IFace + { + } + + export class Derived extends getClass() +>Derived : Derived +>getClass() : IFace +>getClass : () => new () => T +>IFace : IFace + { + } + + export function getClass() : new() => T +>getClass : () => new () => T +>T : T +>T : T + { + return SomeClass as (new() => T); +>SomeClass as (new() => T) : new () => T +>SomeClass : typeof SomeClass +>T : T + } +} + diff --git a/tests/cases/compiler/declarationEmitExpressionInExtends5.ts b/tests/cases/compiler/declarationEmitExpressionInExtends5.ts new file mode 100644 index 00000000000..5057ade7570 --- /dev/null +++ b/tests/cases/compiler/declarationEmitExpressionInExtends5.ts @@ -0,0 +1,20 @@ +// @declaration: true +namespace Test +{ + export interface IFace + { + } + + export class SomeClass implements IFace + { + } + + export class Derived extends getClass() + { + } + + export function getClass() : new() => T + { + return SomeClass as (new() => T); + } +} From 1225c4e0d9d86d96262a368c36979701736e00b8 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Wed, 10 May 2017 11:51:07 -0700 Subject: [PATCH 147/282] Fix lint --- src/compiler/declarationEmitter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 427f1bbd26e..7c842de277f 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -67,7 +67,7 @@ namespace ts { let errorNameNode: DeclarationName; const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments; const emit = compilerOptions.stripInternal ? stripInternal : emitNode; - let needsDeclare: boolean = true; + let needsDeclare = true; let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; From 2e36c83f775159f3179cd7496f0d8cd5c68c7177 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 10 May 2017 11:40:15 -0700 Subject: [PATCH 148/282] isDeclarationName: Return false for LHS of `import { x as y }` and `export { x as y }` --- src/compiler/checker.ts | 19 ++++++++++++++-- src/compiler/utilities.ts | 22 ++++++------------- .../fourslash/findAllRefsOnImportAliases2.ts | 8 +++---- .../fourslash/findAllRefsReExportLocal.ts | 2 +- tests/cases/fourslash/findAllRefsReExports.ts | 6 ++--- .../cases/fourslash/findAllRefsReExports2.ts | 14 ++++++++++++ .../findAllRefsRenameImportWithSameName.ts | 2 +- .../fourslash/renameImportOfExportEquals2.ts | 4 ++-- .../fourslash/renameImportOfReExport2.ts | 2 +- .../fourslash/transitiveExportImports3.ts | 2 +- 10 files changed, 50 insertions(+), 31 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsReExports2.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dfccfca1b8f..f17d7a40f58 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22254,7 +22254,7 @@ namespace ts { return undefined; } - if (isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -22401,7 +22401,7 @@ namespace ts { return getTypeOfSymbol(symbol); } - if (isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { const symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -24430,4 +24430,19 @@ namespace ts { return result; } } + + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name: Node): boolean { + switch (name.parent.kind) { + case SyntaxKind.ImportSpecifier: + case SyntaxKind.ExportSpecifier: + if ((name.parent as ImportOrExportSpecifier).propertyName) { + return true; + } + // falls through + default: + return isDeclarationName(name); + + } + } } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 460a9860f1e..95b76286c59 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1758,22 +1758,14 @@ namespace ts { // True if the given identifier, string literal, or number literal is the name of a declaration node export function isDeclarationName(name: Node): boolean { - if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) { - return false; + switch (name.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - - const parent = name.parent; - if (parent.kind === SyntaxKind.ImportSpecifier || parent.kind === SyntaxKind.ExportSpecifier) { - if ((parent).propertyName) { - return true; - } - } - - if (isDeclaration(parent)) { - return parent.name === name; - } - - return false; } export function getNameOfDeclaration(declaration: Declaration): DeclarationName { diff --git a/tests/cases/fourslash/findAllRefsOnImportAliases2.ts b/tests/cases/fourslash/findAllRefsOnImportAliases2.ts index 63fb12f5270..64f44018d07 100644 --- a/tests/cases/fourslash/findAllRefsOnImportAliases2.ts +++ b/tests/cases/fourslash/findAllRefsOnImportAliases2.ts @@ -1,16 +1,14 @@ /// //@Filename: a.ts -////export class [|{| "isWriteAccess": true, "isDefinition": true |}Class|] { -////} +////export class [|{| "isWriteAccess": true, "isDefinition": true |}Class|] {} //@Filename: b.ts -////import { [|{| "isWriteAccess": true, "isDefinition": true |}Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C2|] } from "./a"; -//// +////import { [|Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C2|] } from "./a"; ////var c = new [|C2|](); //@Filename: c.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C3|] } from "./a"; +////export { [|Class|] as [|{| "isWriteAccess": true, "isDefinition": true |}C3|] } from "./a"; const ranges = test.rangesByText(); const classRanges = ranges.get("Class"); diff --git a/tests/cases/fourslash/findAllRefsReExportLocal.ts b/tests/cases/fourslash/findAllRefsReExportLocal.ts index 25e8accbbc0..3e5890e6317 100644 --- a/tests/cases/fourslash/findAllRefsReExportLocal.ts +++ b/tests/cases/fourslash/findAllRefsReExportLocal.ts @@ -5,7 +5,7 @@ // @Filename: /a.ts ////var [|{| "isWriteAccess": true, "isDefinition": true |}x|]; ////export { [|{| "isWriteAccess": true, "isDefinition": true |}x|] }; -////export { [|{| "isWriteAccess": true, "isDefinition": true |}x|] as [|{| "isWriteAccess": true, "isDefinition": true |}y|] }; +////export { [|x|] as [|{| "isWriteAccess": true, "isDefinition": true |}y|] }; // @Filename: /b.ts ////import { [|{| "isWriteAccess": true, "isDefinition": true |}x|], [|{| "isWriteAccess": true, "isDefinition": true |}y|] } from "./a"; diff --git a/tests/cases/fourslash/findAllRefsReExports.ts b/tests/cases/fourslash/findAllRefsReExports.ts index 593db568c8a..a4cced049b9 100644 --- a/tests/cases/fourslash/findAllRefsReExports.ts +++ b/tests/cases/fourslash/findAllRefsReExports.ts @@ -4,10 +4,10 @@ ////export function [|{| "isWriteAccess": true, "isDefinition": true |}foo|](): void {} // @Filename: /b.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}bar|] } from "./a"; +////export { [|foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}bar|] } from "./a"; // @Filename: /c.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}default|] } from "./a"; +////export { [|foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}default|] } from "./a"; // @Filename: /d.ts ////export { [|{| "isWriteAccess": true, "isDefinition": true |}default|] } from "./c"; @@ -15,7 +15,7 @@ // @Filename: /e.ts ////import { [|{| "isWriteAccess": true, "isDefinition": true |}bar|] } from "./b"; ////import [|{| "isWriteAccess": true, "isDefinition": true |}baz|] from "./c"; -////import { [|{| "isWriteAccess": true, "isDefinition": true |}default|] as [|{| "isWriteAccess": true, "isDefinition": true |}bang|] } from "./c"; +////import { [|default|] as [|{| "isWriteAccess": true, "isDefinition": true |}bang|] } from "./c"; ////import [|{| "isWriteAccess": true, "isDefinition": true |}boom|] from "./d"; ////[|bar|](); [|baz|](); [|bang|](); [|boom|](); diff --git a/tests/cases/fourslash/findAllRefsReExports2.ts b/tests/cases/fourslash/findAllRefsReExports2.ts new file mode 100644 index 00000000000..5dfdc8aebbf --- /dev/null +++ b/tests/cases/fourslash/findAllRefsReExports2.ts @@ -0,0 +1,14 @@ +/// + +// @Filename: /a.ts +////export function [|{| "isWriteAccess": true, "isDefinition": true |}foo|](): void {} + +// @Filename: /b.ts +////import { [|foo|] as [|{| "isWriteAccess": true, "isDefinition": true |}oof|] } from "./a"; + +verify.noErrors(); +const [r0, r1, r2] = test.ranges(); +verify.referenceGroups(r0, [ + { definition: "function foo(): void", ranges: [r0, r1] }, + { definition: "import oof", ranges: [r2] } +]); diff --git a/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts b/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts index c1a49b3b5b0..5a5db1496a7 100644 --- a/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts +++ b/tests/cases/fourslash/findAllRefsRenameImportWithSameName.ts @@ -4,7 +4,7 @@ ////export const [|{| "isWriteAccess": true, "isDefinition": true |}x|] = 0; //@Filename: /b.ts -////import { [|{| "isWriteAccess": true, "isDefinition": true |}x|] as [|{| "isWriteAccess": true, "isDefinition": true |}x|] } from "./a"; +////import { [|x|] as [|{| "isWriteAccess": true, "isDefinition": true |}x|] } from "./a"; ////[|x|]; verify.noErrors(); diff --git a/tests/cases/fourslash/renameImportOfExportEquals2.ts b/tests/cases/fourslash/renameImportOfExportEquals2.ts index f57a10c5777..8ac00b8c012 100644 --- a/tests/cases/fourslash/renameImportOfExportEquals2.ts +++ b/tests/cases/fourslash/renameImportOfExportEquals2.ts @@ -8,10 +8,10 @@ ////} ////declare module "a" { //// import * as [|{| "isWriteAccess": true, "isDefinition": true |}O|] from "mod"; -//// export { [|{| "isWriteAccess": true, "isDefinition": true |}O|] as [|{| "isWriteAccess": true, "isDefinition": true |}P|] }; // Renaming N here would rename +//// export { [|O|] as [|{| "isWriteAccess": true, "isDefinition": true |}P|] }; // Renaming N here would rename ////} ////declare module "b" { -//// import { [|{| "isWriteAccess": true, "isDefinition": true |}P|] as [|{| "isWriteAccess": true, "isDefinition": true |}Q|] } from "a"; +//// import { [|P|] as [|{| "isWriteAccess": true, "isDefinition": true |}Q|] } from "a"; //// export const y: typeof [|Q|].x; ////} diff --git a/tests/cases/fourslash/renameImportOfReExport2.ts b/tests/cases/fourslash/renameImportOfReExport2.ts index 56cc3966112..ac61200b2f0 100644 --- a/tests/cases/fourslash/renameImportOfReExport2.ts +++ b/tests/cases/fourslash/renameImportOfReExport2.ts @@ -4,7 +4,7 @@ //// export class [|{| "isWriteAccess": true, "isDefinition": true |}C|] {} ////} ////declare module "b" { -//// export { [|{| "isWriteAccess": true, "isDefinition": true |}C|] as [|{| "isWriteAccess": true, "isDefinition": true |}D|] } from "a"; +//// export { [|C|] as [|{| "isWriteAccess": true, "isDefinition": true |}D|] } from "a"; ////} ////declare module "c" { //// import { [|{| "isWriteAccess": true, "isDefinition": true |}D|] } from "b"; diff --git a/tests/cases/fourslash/transitiveExportImports3.ts b/tests/cases/fourslash/transitiveExportImports3.ts index 6b3bb10572d..638fa85df83 100644 --- a/tests/cases/fourslash/transitiveExportImports3.ts +++ b/tests/cases/fourslash/transitiveExportImports3.ts @@ -4,7 +4,7 @@ ////export function [|{| "isWriteAccess": true, "isDefinition": true |}f|]() {} // @Filename: b.ts -////export { [|{| "isWriteAccess": true, "isDefinition": true |}f|] as [|{| "isWriteAccess": true, "isDefinition": true |}g|] } from "./a"; +////export { [|f|] as [|{| "isWriteAccess": true, "isDefinition": true |}g|] } from "./a"; ////import { [|{| "isWriteAccess": true, "isDefinition": true |}f|] } from "./a"; ////import { [|{| "isWriteAccess": true, "isDefinition": true |}g|] } from "./b"; From e26d2ae1394538bdcf9436a9ba5654c1c8ec28f8 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 10 May 2017 12:11:44 -0700 Subject: [PATCH 149/282] An enum should include a Namespace SemanticMeaning --- src/services/utilities.ts | 4 +++- tests/cases/fourslash/findAllRefsEnumAsNamespace.ts | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/findAllRefsEnumAsNamespace.ts diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 065c42245f6..688d3fc9643 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -41,9 +41,11 @@ namespace ts { return SemanticMeaning.Type; case SyntaxKind.ClassDeclaration: - case SyntaxKind.EnumDeclaration: return SemanticMeaning.Value | SemanticMeaning.Type; + case SyntaxKind.EnumDeclaration: + return SemanticMeaning.All; + case SyntaxKind.ModuleDeclaration: if (isAmbientModule(node)) { return SemanticMeaning.Namespace | SemanticMeaning.Value; diff --git a/tests/cases/fourslash/findAllRefsEnumAsNamespace.ts b/tests/cases/fourslash/findAllRefsEnumAsNamespace.ts new file mode 100644 index 00000000000..a065f355d10 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsEnumAsNamespace.ts @@ -0,0 +1,6 @@ +/// + +////enum [|{| "isWriteAccess": true, "isDefinition": true |}E|] { A } +////let e: [|E|].A; + +verify.singleReferenceGroup("enum E"); From f3fe0138a25086617d751e0ce4a762869ff4faf2 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 10 May 2017 12:20:46 -0700 Subject: [PATCH 150/282] Also make EnumMember have Type meaning --- src/services/utilities.ts | 4 ++-- tests/cases/fourslash/findAllRefsEnumMember.ts | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsEnumMember.ts diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 688d3fc9643..4ae9204f7ed 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -21,7 +21,6 @@ namespace ts { case SyntaxKind.PropertySignature: case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: - case SyntaxKind.EnumMember: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: @@ -40,6 +39,7 @@ namespace ts { case SyntaxKind.TypeLiteral: return SemanticMeaning.Type; + case SyntaxKind.EnumMember: case SyntaxKind.ClassDeclaration: return SemanticMeaning.Value | SemanticMeaning.Type; @@ -63,7 +63,7 @@ namespace ts { case SyntaxKind.ImportDeclaration: case SyntaxKind.ExportAssignment: case SyntaxKind.ExportDeclaration: - return SemanticMeaning.Value | SemanticMeaning.Type | SemanticMeaning.Namespace; + return SemanticMeaning.All; // An external module can be a Value case SyntaxKind.SourceFile: diff --git a/tests/cases/fourslash/findAllRefsEnumMember.ts b/tests/cases/fourslash/findAllRefsEnumMember.ts new file mode 100644 index 00000000000..584b8befd29 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsEnumMember.ts @@ -0,0 +1,6 @@ +/// + +////enum E { [|{| "isWriteAccess": true, "isDefinition": true |}A|], B } +////const e: E.[|A|] = E.[|A|]; + +verify.singleReferenceGroup("(enum member) E.A = 0"); From f05a85d56fe1a627cef508773ce04e6d52b50569 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 10 May 2017 15:49:40 -0700 Subject: [PATCH 151/282] Fix bug for goto-definition on a TSX constructor using an alias declaration --- src/compiler/checker.ts | 2 +- src/compiler/types.ts | 2 +- src/services/goToDefinition.ts | 23 +++---------------- .../tsxGoToDefinitionClassInDifferentFile.ts | 15 ++++++++++++ 4 files changed, 20 insertions(+), 22 deletions(-) create mode 100644 tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dfccfca1b8f..97bebeadfb3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12755,7 +12755,7 @@ namespace ts { * @param node the expression whose contextual type will be returned. * @returns the contextual type of an expression. */ - function getContextualType(node: Expression): Type { + function getContextualType(node: Expression): Type | undefined { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 74670352c34..d89c7877da6 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2528,7 +2528,7 @@ namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; + getContextualType(node: Expression): Type | undefined; getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 09d1f2a248c..07b1e4448bd 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -85,17 +85,6 @@ namespace ts.GoToDefinition { declaration => createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); } - if (isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - const {symbolName, symbolKind, containerName} = getSymbolInfo(typeChecker, symbol, node); - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } - // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -106,15 +95,9 @@ namespace ts.GoToDefinition { // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) const element = getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent as Expression)) { - const result: DefinitionInfo[] = []; - const propertySymbols = getPropertySymbolsFromContextualType(typeChecker, element); - for (const propertySymbol of propertySymbols) { - result.push(...getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent as Expression)) { + return flatMap(getPropertySymbolsFromContextualType(typeChecker, element), propertySymbol => + getDefinitionFromSymbol(typeChecker, propertySymbol, node)); } return getDefinitionFromSymbol(typeChecker, symbol, node); } diff --git a/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts b/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts new file mode 100644 index 00000000000..f217e4096fc --- /dev/null +++ b/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts @@ -0,0 +1,15 @@ +/// + +// @jsx: preserve + +// @Filename: C.tsx +////export default class C {} + +// @Filename: a.tsx +////import /*def*/C from "./C"; +////const foo = ; + +verify.noErrors(); + +goTo.marker("use"); +verify.goToDefinitionIs("def"); From 578826cd613bc6fb3a18e38d0758f05a8b0d0f3b Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 10 May 2017 16:41:30 -0700 Subject: [PATCH 152/282] Adds definitions for the es2017 Atomics global object --- src/lib/es2017.sharedmemory.d.ts | 93 +++++++++++++++++++++++++++++++- src/lib/es5.d.ts | 48 ++++++++++------- 2 files changed, 120 insertions(+), 21 deletions(-) diff --git a/src/lib/es2017.sharedmemory.d.ts b/src/lib/es2017.sharedmemory.d.ts index e18390a5591..b9a9b0f7e10 100644 --- a/src/lib/es2017.sharedmemory.d.ts +++ b/src/lib/es2017.sharedmemory.d.ts @@ -23,5 +23,96 @@ interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; new (byteLength: number): SharedArrayBuffer; } +declare var SharedArrayBuffer: SharedArrayBufferConstructor; -declare var SharedArrayBuffer: SharedArrayBufferConstructor; \ No newline at end of file +interface ArrayBufferTypes { + SharedArrayBuffer: SharedArrayBuffer; +} + +interface Atomics { + /** + * Adds a value to the value at the given position in the array, returning the original value. + * Until this atomic operation completes, any other read or write operation against the array + * will block. + */ + add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores the bitwise AND of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or + * write operation against the array will block. + */ + and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Replaces the value at the given position in the array if the original value equals the given + * expected value, returning the original value. Until this atomic operation completes, any + * other read or write operation against the array will block. + */ + compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + + /** + * Replaces the value at the given position in the array, returning the original value. Until + * this atomic operation completes, any other read or write operation against the array will + * block. + */ + exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Returns a value indicating whether high-performance algorithms can use atomic operations + * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed + * array. + */ + isLockFree(size: number): boolean; + + /** + * Returns the value at the given position in the array. Until this atomic operation completes, + * any other read or write operation against the array will block. + */ + load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + + /** + * Stores the bitwise OR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores a value at the given position in the array, returning the new value. Until this + * atomic operation completes, any other read or write operation against the array will block. + */ + store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Subtracts a value from the value at the given position in the array, returning the original + * value. Until this atomic operation completes, any other read or write operation against the + * array will block. + */ + sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * If the value at the given position in the array is equal to the provided value, the current + * agent is put to sleep causing execution to suspend until the timeout expires (returning + * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns + * `"not-equal"`. + */ + wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; + + /** + * Wakes up sleeping agents that are waiting on the given index of the array, returning the + * number of agents that were awoken. + */ + wake(typedArray: Int32Array, index: number, count: number): number; + + /** + * Stores the bitwise XOR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + readonly [Symbol.toStringTag]: "Atomics"; +} + +declare var Atomics: Atomics; \ No newline at end of file diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 23805495b69..3a85f4ddad9 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -1386,6 +1386,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1397,7 +1405,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1539,7 +1547,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1556,7 +1564,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1799,7 +1807,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1840,7 +1848,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2084,7 +2092,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2125,7 +2133,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2369,7 +2377,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2409,7 +2417,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2653,7 +2661,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2694,7 +2702,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2938,7 +2946,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2978,7 +2986,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3222,7 +3230,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3262,7 +3270,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3506,7 +3514,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3546,7 +3554,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3790,7 +3798,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3831,7 +3839,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4075,7 +4083,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. From 3c8732fab1cdc524c1cf3a506bda871b09842199 Mon Sep 17 00:00:00 2001 From: Charles Pierce Date: Wed, 10 May 2017 17:26:47 -0700 Subject: [PATCH 153/282] Prevent Duplicate String Literal Completions --- src/services/completions.ts | 23 +++++++++++-------- .../fourslash/completionForStringLiteral12.ts | 10 ++++++++ 2 files changed, 24 insertions(+), 9 deletions(-) create mode 100644 tests/cases/fourslash/completionForStringLiteral12.ts diff --git a/src/services/completions.ts b/src/services/completions.ts index 318c02683ff..948d7349419 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -221,11 +221,12 @@ namespace ts.Completions { function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo: SignatureHelp.ArgumentListInfo, typeChecker: TypeChecker): CompletionInfo | undefined { const candidates: Signature[] = []; const entries: CompletionEntry[] = []; + const uniques = createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (const candidate of candidates) { - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { @@ -258,7 +259,7 @@ namespace ts.Completions { return undefined; } - function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker): void { + function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker, uniques = createMap()): void { if (type && type.flags & TypeFlags.TypeParameter) { type = typeChecker.getBaseConstraintOfType(type); } @@ -267,16 +268,20 @@ namespace ts.Completions { } if (type.flags & TypeFlags.Union) { for (const t of (type).types) { - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & TypeFlags.StringLiteral) { - result.push({ - name: (type).text, - kindModifiers: ScriptElementKindModifier.none, - kind: ScriptElementKind.variableElement, - sortText: "0" - }); + const name = (type).text; + if (!uniques.get(name)) { + uniques.set(name, name); + result.push({ + name, + kindModifiers: ScriptElementKindModifier.none, + kind: ScriptElementKind.variableElement, + sortText: "0" + }); + } } } diff --git a/tests/cases/fourslash/completionForStringLiteral12.ts b/tests/cases/fourslash/completionForStringLiteral12.ts new file mode 100644 index 00000000000..22bb2f00a43 --- /dev/null +++ b/tests/cases/fourslash/completionForStringLiteral12.ts @@ -0,0 +1,10 @@ +/// + +////function foo(x: "bla"): void; +////function foo(x: "bla"): void; +////function foo(x: string) {} +////foo("/**/") + +goTo.marker(); +verify.completionListContains("bla"); +verify.completionListCount(1); From 5c5b5e9a3b3b22dd26ee08d9d670ef826dc13454 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 11 May 2017 09:06:01 -0700 Subject: [PATCH 154/282] Fail on bad moduleResolution kind --- src/compiler/moduleNameResolver.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index f984c12fb68..acf01bac905 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -442,6 +442,8 @@ namespace ts { case ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); } if (perFolderCache) { From ac6018aa955147838aacbdce9c4d0604a9b634be Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Wed, 10 May 2017 17:01:05 -0700 Subject: [PATCH 155/282] type arguments in qualified names --- src/compiler/checker.ts | 74 ++++++++++++++++++++++++++++++----------- src/compiler/types.ts | 12 +++---- 2 files changed, 60 insertions(+), 26 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 82567bc170d..ed5c7ea669e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2448,9 +2448,10 @@ namespace ts { if (!inTypeAlias && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { - const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); - const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); + const name = symbolToTypeReferenceName(type.aliasSymbol); + const typeArgumentNodes = toTypeArgumentNodes(type.aliasTypeArguments, context); return createTypeReferenceNode(name, typeArgumentNodes); + // return symbolToTypeReferenceIdentifier(type.aliasSymbol, type.aliasTypeArguments); } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { @@ -2614,6 +2615,13 @@ namespace ts { return createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol: Symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + const entityName = symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.name) ? symbolToName(symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context) : createIdentifier(""); + // TODO: assert no type args? + return entityName; + } + function typeReferenceToTypeNode(type: TypeReference) { const typeArguments: Type[] = type.typeArguments || emptyArray; if (type.target === globalArrayType) { @@ -2641,7 +2649,7 @@ namespace ts { else { const outerTypeParameters = type.target.outerTypeParameters; let i = 0; - let qualifiedName: QualifiedName | undefined = undefined; + let qualifiedName: QualifiedName | undefined; if (outerTypeParameters) { let inFirstTypeArgument = true; const length = outerTypeParameters.length; @@ -2655,46 +2663,68 @@ namespace ts { // 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 (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { - const qualifiedNamePartTypeArguments = typeArguments.slice(start,i); - const qualifiedNamePartTypeArgumentNodes = qualifiedNamePartTypeArguments && createNodeArray(mapToTypeNodeArray(qualifiedNamePartTypeArguments, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true)); - const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true, SymbolFlags.Type, context); - qualifiedNamePart.typeArguments = qualifiedNamePartTypeArgumentNodes; + const typeArgumentNodes = createNodeArray(toTypeArgumentNodes(typeArguments.slice(start, i), context)); + const namePart = symbolToTypeReferenceName(parent); + (namePart.kind === SyntaxKind.Identifier ? namePart : namePart.right).typeArguments = typeArgumentNodes; - if (!qualifiedName) { - qualifiedName = createQualifiedName(qualifiedNamePart, /*right*/ undefined); + if (qualifiedName) { + Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = createQualifiedName(qualifiedName, /*right*/ undefined); } else { - Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = createQualifiedName(namePart, /*right*/ undefined); } } inFirstTypeArgument = false; } } + let entityName: EntityName = undefined; - const nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true, SymbolFlags.Type, context); + const nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - const typeParameterCount = (type.target.typeParameters || emptyArray).length; let typeArgumentNodes: TypeNode[] | undefined; if (some(typeArguments)) { - const slice = typeArguments.slice(i, typeParameterCount - i); - context.InFirstTypeArgument = true; - typeArgumentNodes = mapToTypeNodeArray(slice, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); + const typeParameterCount = (type.target.typeParameters || emptyArray).length; + const slice = typeArguments && typeArguments.slice(i, typeParameterCount); + typeArgumentNodes = toTypeArgumentNodes(slice, context); + } + + if (typeArgumentNodes) { + const lastIdentifier = entityName.kind === SyntaxKind.Identifier ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; } return createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left: QualifiedName, right: Identifier | QualifiedName) { + Debug.assert(left.right === undefined); + + if (right.kind === SyntaxKind.Identifier) { + left.right = right; + return left; + } + + let rightPart = right; + while (rightPart.left.kind !== SyntaxKind.Identifier) { + rightPart = rightPart.left; + } + + left.right = rightPart.left; + rightPart.left = left; + return right; + } + function createTypeNodesFromResolvedType(resolvedType: ResolvedType): TypeElement[] { const typeElements: TypeElement[] = []; for (const signature of resolvedType.callSignatures) { @@ -2754,7 +2784,7 @@ namespace ts { const result = []; Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); for (let i = 0; i < types.length; ++i) { - let type = types[i] + const type = types[i]; context.InElementType = addInElementTypeFlag; if (i === 0) { context.InFirstTypeArgument = addInFirstTypeArgumentFlag; @@ -2768,6 +2798,10 @@ namespace ts { return result; } + function toTypeArgumentNodes(typeArguments: Type[], context: NodeBuilderContext) { + return typeArguments && mapToTypeNodeArray(typeArguments, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword); const name = getNameFromIndexInfo(indexInfo) || "x"; @@ -2913,7 +2947,7 @@ namespace ts { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowTypeParameterInQualifiedName)) { context.encounteredError = true; } - typeParameterNodes = typeParameters && mapToTypeNodeArray(typeParameters, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); + typeParameterNodes = toTypeArgumentNodes(typeParameters, context); } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index ad89069c286..73d6067cb10 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -570,12 +570,12 @@ namespace ts { export interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; - text: string; // Text of identifier (with escapes converted to characters) - originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later - /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. - /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. - isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace - /*@internal*/ typeArguments: NodeArray; // Only defined on synthesized nodes.Though not syntactically valid, used in emitting diagnostics. + text: string; // Text of identifier (with escapes converted to characters) + originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later + /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. + /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. + isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace + /*@internal*/ typeArguments?: NodeArray; // Only defined on synthesized nodes.Though not syntactically valid, used in emitting diagnostics. } // Transient identifier node (marked by id === -1) From cff19ab3d3fc2cb8d405a9c435b364b5b81985c8 Mon Sep 17 00:00:00 2001 From: Charles Pierce Date: Thu, 11 May 2017 10:42:25 -0700 Subject: [PATCH 156/282] Switch map to be used as a set rather than a map --- src/services/completions.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index 948d7349419..e850bfb4496 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -221,7 +221,7 @@ namespace ts.Completions { function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo: SignatureHelp.ArgumentListInfo, typeChecker: TypeChecker): CompletionInfo | undefined { const candidates: Signature[] = []; const entries: CompletionEntry[] = []; - const uniques = createMap(); + const uniques = createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); @@ -259,7 +259,7 @@ namespace ts.Completions { return undefined; } - function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker, uniques = createMap()): void { + function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker, uniques = createMap()): void { if (type && type.flags & TypeFlags.TypeParameter) { type = typeChecker.getBaseConstraintOfType(type); } @@ -273,8 +273,8 @@ namespace ts.Completions { } else if (type.flags & TypeFlags.StringLiteral) { const name = (type).text; - if (!uniques.get(name)) { - uniques.set(name, name); + if (!uniques.has(name)) { + uniques.set(name, true); result.push({ name, kindModifiers: ScriptElementKindModifier.none, From e76c96ce547e670789da978cdcb64e7c72c6cb27 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 11 May 2017 11:37:28 -0700 Subject: [PATCH 157/282] Allow references to ambient block scoped variables Even when 1. --out or --outfile is specified 2. The block scoped variable's file is after the referrer's file. --- src/compiler/checker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 861279b2225..82c3eaaf04b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -737,7 +737,8 @@ namespace ts { const useFile = getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } From 7803c1ce17ec8a862c3d3c207587fd72eb1d3d94 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 11 May 2017 11:38:26 -0700 Subject: [PATCH 158/282] Test:reference ambient block scoped vars in different file --- .../blockScopedNamespaceDifferentFile.js | 35 ++++++++++++++ .../blockScopedNamespaceDifferentFile.symbols | 44 ++++++++++++++++++ .../blockScopedNamespaceDifferentFile.types | 46 +++++++++++++++++++ .../blockScopedNamespaceDifferentFile.ts | 22 +++++++++ 4 files changed, 147 insertions(+) create mode 100644 tests/baselines/reference/blockScopedNamespaceDifferentFile.js create mode 100644 tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols create mode 100644 tests/baselines/reference/blockScopedNamespaceDifferentFile.types create mode 100644 tests/cases/compiler/blockScopedNamespaceDifferentFile.ts diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.js b/tests/baselines/reference/blockScopedNamespaceDifferentFile.js new file mode 100644 index 00000000000..3eab7477c09 --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.js @@ -0,0 +1,35 @@ +//// [tests/cases/compiler/blockScopedNamespaceDifferentFile.ts] //// + +//// [test.ts] +// #15734 failed when test.ts comes before typings.d.ts +namespace C { + export class Name { + static funcData = A.AA.func(); + static someConst = A.AA.foo; + + constructor(parameters) {} + } +} + +//// [typings.d.ts] +declare namespace A { + namespace AA { + function func(): number; + const foo = ""; + } +} + + +//// [out.js] +// #15734 failed when test.ts comes before typings.d.ts +var C; +(function (C) { + var Name = (function () { + function Name(parameters) { + } + return Name; + }()); + Name.funcData = A.AA.func(); + Name.someConst = A.AA.foo; + C.Name = Name; +})(C || (C = {})); diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols b/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols new file mode 100644 index 00000000000..b7192d0e12b --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols @@ -0,0 +1,44 @@ +=== tests/cases/compiler/test.ts === +// #15734 failed when test.ts comes before typings.d.ts +namespace C { +>C : Symbol(C, Decl(test.ts, 0, 0)) + + export class Name { +>Name : Symbol(Name, Decl(test.ts, 1, 13)) + + static funcData = A.AA.func(); +>funcData : Symbol(Name.funcData, Decl(test.ts, 2, 23)) +>A.AA.func : Symbol(A.AA.func, Decl(typings.d.ts, 1, 18)) +>A.AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) +>AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>func : Symbol(A.AA.func, Decl(typings.d.ts, 1, 18)) + + static someConst = A.AA.foo; +>someConst : Symbol(Name.someConst, Decl(test.ts, 3, 38)) +>A.AA.foo : Symbol(A.AA.foo, Decl(typings.d.ts, 3, 13)) +>A.AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) +>AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>foo : Symbol(A.AA.foo, Decl(typings.d.ts, 3, 13)) + + constructor(parameters) {} +>parameters : Symbol(parameters, Decl(test.ts, 6, 20)) + } +} + +=== tests/cases/compiler/typings.d.ts === +declare namespace A { +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) + + namespace AA { +>AA : Symbol(AA, Decl(typings.d.ts, 0, 21)) + + function func(): number; +>func : Symbol(func, Decl(typings.d.ts, 1, 18)) + + const foo = ""; +>foo : Symbol(foo, Decl(typings.d.ts, 3, 13)) + } +} + diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.types b/tests/baselines/reference/blockScopedNamespaceDifferentFile.types new file mode 100644 index 00000000000..c03d51d2bc4 --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.types @@ -0,0 +1,46 @@ +=== tests/cases/compiler/test.ts === +// #15734 failed when test.ts comes before typings.d.ts +namespace C { +>C : typeof C + + export class Name { +>Name : Name + + static funcData = A.AA.func(); +>funcData : number +>A.AA.func() : number +>A.AA.func : () => number +>A.AA : typeof A.AA +>A : typeof A +>AA : typeof A.AA +>func : () => number + + static someConst = A.AA.foo; +>someConst : string +>A.AA.foo : "" +>A.AA : typeof A.AA +>A : typeof A +>AA : typeof A.AA +>foo : "" + + constructor(parameters) {} +>parameters : any + } +} + +=== tests/cases/compiler/typings.d.ts === +declare namespace A { +>A : typeof A + + namespace AA { +>AA : typeof AA + + function func(): number; +>func : () => number + + const foo = ""; +>foo : "" +>"" : "" + } +} + diff --git a/tests/cases/compiler/blockScopedNamespaceDifferentFile.ts b/tests/cases/compiler/blockScopedNamespaceDifferentFile.ts new file mode 100644 index 00000000000..4a9fe4a2a85 --- /dev/null +++ b/tests/cases/compiler/blockScopedNamespaceDifferentFile.ts @@ -0,0 +1,22 @@ +// @target: es5 +// @outFile: out.js +// @module: amd + +// #15734 failed when test.ts comes before typings.d.ts +// @Filename: test.ts +namespace C { + export class Name { + static funcData = A.AA.func(); + static someConst = A.AA.foo; + + constructor(parameters) {} + } +} + +// @Filename: typings.d.ts +declare namespace A { + namespace AA { + function func(): number; + const foo = ""; + } +} From a8ad40f131c0459d6316ff872cd7e4909d36d71b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 11 May 2017 11:42:36 -0700 Subject: [PATCH 159/282] Add async to the list of class element completion keyword and refactoring according to feedback --- src/harness/fourslash.ts | 3 ++- src/services/completions.ts | 8 ++++---- tests/cases/fourslash/completionEntryForClassMembers.ts | 4 ++++ 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 74790400b98..57d0eb59ee2 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -3426,7 +3426,8 @@ namespace FourSlashInterface { "readonly", "get", "set", - "constructor" + "constructor", + "async" ]; constructor(protected state: FourSlash.TestState, private negative = false) { diff --git a/src/services/completions.ts b/src/services/completions.ts index cb4abb89b58..986ad0fe5ad 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -618,7 +618,8 @@ namespace ts.Completions { if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration - return tryGetClassLikeCompletionSymbols(classLikeContainer); + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { @@ -929,7 +930,7 @@ namespace ts.Completions { * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetClassLikeCompletionSymbols(classLikeDeclaration: ClassLikeDeclaration): boolean { + function getGetClassLikeCompletionSymbols(classLikeDeclaration: ClassLikeDeclaration) { // We're looking up possible property names from parent type. isMemberCompletion = true; // Declaring new property/method/accessor @@ -965,8 +966,6 @@ namespace ts.Completions { baseProperty => baseProperty.getDeclarations() && !(getDeclarationModifierFlagsFromSymbol(baseProperty) & ModifierFlags.Private)); } } - - return true; } /** @@ -1431,6 +1430,7 @@ namespace ts.Completions { case SyntaxKind.ReadonlyKeyword: case SyntaxKind.GetKeyword: case SyntaxKind.SetKeyword: + case SyntaxKind.AsyncKeyword: return true; } } diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts index 672046f62a7..8cea37d3b1e 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -84,6 +84,9 @@ ////class M extends B { //// private static identi/*classThatStartedWritingIdentifierAfterPrivateStaticModifier*/ ////} +////class N extends B { +//// async /*classThatHasWrittenAsyncKeyword*/ +////} const allowedKeywordCount = verify.allowedClassElementKeywords.length; type CompletionInfo = [string, string]; @@ -171,6 +174,7 @@ const classInstanceElementLocations = [ "classThatStartedWritingIdentifierOfGetAccessor", "classThatStartedWritingIdentifierOfSetAccessor", "classThatStartedWritingIdentifierAfterModifier", + "classThatHasWrittenAsyncKeyword" ]; verifyClassElementLocations(instanceMemberInfo, classInstanceElementLocations); From 20a70f99b108870327d5807ff1b5d97370d46111 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 11 May 2017 11:58:54 -0700 Subject: [PATCH 160/282] findAllReferences: Clean up uses of `getWidth` and `getStart` --- src/services/findAllReferences.ts | 34 +++++++++++++------------------ 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 7be2229877a..2363f59a774 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -637,7 +637,9 @@ namespace ts.FindAllReferences.Core { return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, start: number, end: number): number[] { + function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile, fullStart = false): number[] { + const start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + const end = container.getEnd(); const positions: number[] = []; /// TODO: Cache symbol existence for files to save text search @@ -676,16 +678,11 @@ namespace ts.FindAllReferences.Core { const references: Entry[] = []; const sourceFile = container.getSourceFile(); const labelName = targetLabel.text; - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (const position of possiblePositions) { const node = getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel))) { references.push(nodeEntry(node)); } } @@ -697,15 +694,14 @@ namespace ts.FindAllReferences.Core { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case SyntaxKind.Identifier: - return node.getWidth() === searchSymbolName.length; + return (node as Identifier).text.length === searchSymbolName.length; case SyntaxKind.StringLiteral: return (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + (node as StringLiteral).text.length === searchSymbolName.length; case SyntaxKind.NumericLiteral: - return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && (node as NumericLiteral).text.length === searchSymbolName.length; default: return false; @@ -722,7 +718,7 @@ namespace ts.FindAllReferences.Core { } function addReferencesForKeywordInFile(sourceFile: SourceFile, kind: SyntaxKind, searchText: string, references: Push): void { - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (const position of possiblePositions) { const referenceLocation = getTouchingPropertyName(sourceFile, position); if (referenceLocation.kind === kind) { @@ -746,9 +742,7 @@ namespace ts.FindAllReferences.Core { return; } - const start = state.findInComments ? container.getFullStart() : container.getStart(); - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (const position of possiblePositions) { + for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments)) { getReferencesAtLocation(sourceFile, position, search, state); } } @@ -1192,7 +1186,7 @@ namespace ts.FindAllReferences.Core { const references: Entry[] = []; const sourceFile = searchSpaceNode.getSourceFile(); - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); for (const position of possiblePositions) { const node = getTouchingWord(sourceFile, position); @@ -1254,13 +1248,13 @@ namespace ts.FindAllReferences.Core { if (searchSpaceNode.kind === SyntaxKind.SourceFile) { forEach(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { const sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } @@ -1314,7 +1308,7 @@ namespace ts.FindAllReferences.Core { for (const sourceFile of sourceFiles) { cancellationToken.throwIfCancellationRequested(); - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } From 6d6cdac645226c27d43950e1030ff31fe5bbf9b8 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 11 May 2017 12:22:10 -0700 Subject: [PATCH 161/282] Handle escaped identifiers --- src/compiler/types.ts | 6 +++++- src/services/findAllReferences.ts | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 74670352c34..d3e087434d9 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -571,7 +571,11 @@ namespace ts { export interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; - text: string; // Text of identifier (with escapes converted to characters) + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ + text: string; originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 2363f59a774..395c282f6d5 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -694,7 +694,7 @@ namespace ts.FindAllReferences.Core { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case SyntaxKind.Identifier: - return (node as Identifier).text.length === searchSymbolName.length; + return unescapeIdentifier((node as Identifier).text).length === searchSymbolName.length; case SyntaxKind.StringLiteral: return (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && From 9520108b9f2fda65034f6f6a84a82f15b40cac4d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 11 May 2017 13:18:46 -0700 Subject: [PATCH 162/282] Move Levenshtein distance out of public API I had put it in the wrong half of utilities.ts. --- src/compiler/utilities.ts | 46 +++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 95b76286c59..5725d04a9cf 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4234,6 +4234,29 @@ namespace ts { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); } + + export function levenshtein(s1: string, s2: string): number { + let previous: number[] = new Array(s2.length + 1); + let current: number[] = new Array(s2.length + 1); + for (let i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (let i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (let j = 1; j < s2.length + 1; j++) { + current[j] = Math.min( + previous[j] + 1, + current[j - 1] + 1, + previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + const tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } } namespace ts { @@ -4664,27 +4687,4 @@ namespace ts { export function unescapeIdentifier(identifier: string): string { return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier; } - - export function levenshtein(s1: string, s2: string): number { - let previous: number[] = new Array(s2.length + 1); - let current: number[] = new Array(s2.length + 1); - for (let i = 0; i < s2.length + 1; i++) { - previous[i] = i; - current[i] = -1; - } - for (let i = 1; i < s1.length + 1; i++) { - current[0] = i; - for (let j = 1; j < s2.length + 1; j++) { - current[j] = Math.min( - previous[j] + 1, - current[j - 1] + 1, - previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); - } - // shift current back to previous, and then reuse previous' array - const tmp = previous; - previous = current; - current = tmp; - } - return previous[previous.length - 1]; - } } From 7c89ff7d77b41b64ac440eab34dddfc2c7e3f057 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 11 May 2017 13:39:37 -0700 Subject: [PATCH 163/282] Inline resolvedModuleFromResolved --- src/compiler/moduleNameResolver.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index acf01bac905..12a42b6899c 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -47,13 +47,11 @@ namespace ts { return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved({ path, extension }: Resolved, isExternalLibraryImport: boolean): ResolvedModuleFull { - return { resolvedFileName: path, extension, isExternalLibraryImport }; - } - function createResolvedModuleWithFailedLookupLocations(resolved: Resolved | undefined, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport }, + failedLookupLocations + }; } export function moduleHasNonRelativeName(moduleName: string): boolean { From d5f34da9dd913c201ba00c44b50806b2ca1a0261 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 11 May 2017 14:07:33 -0700 Subject: [PATCH 164/282] Accept baselines and update test --- tests/baselines/reference/escapedIdentifiers.types | 2 +- .../reference/unicodeExtendedEscapesInStrings06_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings06_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings08_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings08_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings09_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings09_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings10_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings10_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings11_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings11_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings13_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings13_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings15_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings15_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings16_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings16_ES6.types | 2 +- .../fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts | 2 +- 18 files changed, 18 insertions(+), 18 deletions(-) diff --git a/tests/baselines/reference/escapedIdentifiers.types b/tests/baselines/reference/escapedIdentifiers.types index 6d48bb3392f..ef6c0983d39 100644 --- a/tests/baselines/reference/escapedIdentifiers.types +++ b/tests/baselines/reference/escapedIdentifiers.types @@ -220,7 +220,7 @@ class testClass { >testClass : testClass public func(arg1: number, arg\u0032: string, arg\u0033: boolean, arg4: number) { ->func : (arg1: number, arg\u0032: string, arg\u0033: boolean, arg4: number) => void +>func : (arg1: number, arg2: string, arg3: boolean, arg4: number) => void >arg1 : number >arg\u0032 : string >arg\u0033 : boolean diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types index 0c742aaf7bd..e6942df5d1e 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types @@ -3,5 +3,5 @@ // 1. Assert: 0 ≤ cp ≤ 0x10FFFF. var x = "\u{10FFFF}"; >x : string ->"\u{10FFFF}" : "􏿿" +>"\u{10FFFF}" : "\uDBFF\uDFFF" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types index 6b98c0c98a7..82cc1fa622b 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types @@ -3,5 +3,5 @@ // 1. Assert: 0 ≤ cp ≤ 0x10FFFF. var x = "\u{10FFFF}"; >x : string ->"\u{10FFFF}" : "􏿿" +>"\u{10FFFF}" : "\uDBFF\uDFFF" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types index 0007b758817..9c316cca313 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types @@ -4,5 +4,5 @@ // (FFFF == 65535) var x = "\u{FFFF}"; >x : string ->"\u{FFFF}" : "￿" +>"\u{FFFF}" : "\uFFFF" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types index aedd2f72ef9..a5982a77c67 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types @@ -4,5 +4,5 @@ // (FFFF == 65535) var x = "\u{FFFF}"; >x : string ->"\u{FFFF}" : "￿" +>"\u{FFFF}" : "\uFFFF" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types index daf8a776e8a..7508721f141 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types @@ -4,5 +4,5 @@ // (10000 == 65536) var x = "\u{10000}"; >x : string ->"\u{10000}" : "𐀀" +>"\u{10000}" : "\uD800\uDC00" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types index 0963f552c96..5f05276ed33 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types @@ -4,5 +4,5 @@ // (10000 == 65536) var x = "\u{10000}"; >x : string ->"\u{10000}" : "𐀀" +>"\u{10000}" : "\uD800\uDC00" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types index a4977300e65..a5422cc7a92 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{D800}"; >x : string ->"\u{D800}" : "�" +>"\u{D800}" : "\uD800" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types index 6d6d0112f08..2fcdd0547ee 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{D800}"; >x : string ->"\u{D800}" : "�" +>"\u{D800}" : "\uD800" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types index 74e6817c85a..b26387baaec 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{DC00}"; >x : string ->"\u{DC00}" : "�" +>"\u{DC00}" : "\uDC00" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types index c1b3f372dab..cd010529996 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{DC00}"; >x : string ->"\u{DC00}" : "�" +>"\u{DC00}" : "\uDC00" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types index 224e81adec5..68eb2fe8de1 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings13_ES5.ts === var x = "\u{DDDDD}"; >x : string ->"\u{DDDDD}" : "󝷝" +>"\u{DDDDD}" : "\uDB37\uDDDD" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types index e69b2af435c..4ad8d2e3f3d 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings13_ES6.ts === var x = "\u{DDDDD}"; >x : string ->"\u{DDDDD}" : "󝷝" +>"\u{DDDDD}" : "\uDB37\uDDDD" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types index 1973bb3790b..8da56115188 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings15_ES5.ts === var x = "\u{abcd}\u{ef12}\u{3456}\u{7890}"; >x : string ->"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "ꯍ㑖碐" +>"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types index 16ae5177f51..613d91afae2 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings15_ES6.ts === var x = "\u{abcd}\u{ef12}\u{3456}\u{7890}"; >x : string ->"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "ꯍ㑖碐" +>"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types index 1ae9d9ef3d5..1b29651e2d7 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings16_ES5.ts === var x = "\u{ABCD}\u{EF12}\u{3456}\u{7890}"; >x : string ->"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "ꯍ㑖碐" +>"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types index a4abc5bdeae..addf7dedff4 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings16_ES6.ts === var x = "\u{ABCD}\u{EF12}\u{3456}\u{7890}"; >x : string ->"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "ꯍ㑖碐" +>"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts index eab4c80c786..f7dfd5e1787 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts @@ -5,7 +5,7 @@ //// class C implements I {[| |]} verify.rangeAfterCodeFix(` - test(a: MyType): void { + test(a: [string, number]): void { throw new Error("Method not implemented."); } `); From 588c4eca427fe598147b17c23b8c47637a5fdac8 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 11 May 2017 13:59:06 -0700 Subject: [PATCH 165/282] Filter out existing members of the class from the completion list --- src/services/completions.ts | 53 +++++++++++++++++-- .../completionEntryForClassMembers.ts | 33 ++++++++++-- 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index 986ad0fe5ad..6be420c0919 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -927,8 +927,6 @@ namespace ts.Completions { /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. */ function getGetClassLikeCompletionSymbols(classLikeDeclaration: ClassLikeDeclaration) { // We're looking up possible property names from parent type. @@ -961,9 +959,8 @@ namespace ts.Completions { typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, classLikeDeclaration) : baseType; - // List of property symbols of base type that are not private - symbols = filter(typeChecker.getPropertiesOfType(typeToGetPropertiesFrom), - baseProperty => baseProperty.getDeclarations() && !(getDeclarationModifierFlagsFromSymbol(baseProperty) & ModifierFlags.Private)); + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList(typeChecker.getPropertiesOfType(typeToGetPropertiesFrom), classLikeDeclaration.members, classElementModifierFlags); } } } @@ -1332,6 +1329,52 @@ namespace ts.Completions { return filter(contextualMemberSymbols, m => !existingMemberNames.get(m.name)); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols: Symbol[], existingMembers: ClassElement[], currentClassElementModifierFlags: ModifierFlags): Symbol[] { + const existingMemberNames = createMap(); + for (const m of existingMembers) { + // Ignore omitted expressions for missing members + if (m.kind !== SyntaxKind.PropertyDeclaration && + m.kind !== SyntaxKind.MethodDeclaration && + m.kind !== SyntaxKind.GetAccessor && + m.kind !== SyntaxKind.SetAccessor) { + continue; + } + + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + + // Dont filter member even if the name matches if it is declared private in the list + if (hasModifier(m, ModifierFlags.Private)) { + continue; + } + + // do not filter it out if the static presence doesnt match + const mIsStatic = hasModifier(m, ModifierFlags.Static); + const currentElementIsStatic = !!(currentClassElementModifierFlags & ModifierFlags.Static); + if ((mIsStatic && currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + + const existingName = getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + + return filter(baseSymbols, baseProperty => + !existingMemberNames.get(baseProperty.name) && + baseProperty.getDeclarations() && + !(getDeclarationModifierFlagsFromSymbol(baseProperty) & ModifierFlags.Private)); + } + /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts index 8cea37d3b1e..b242ca7ed78 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -17,6 +17,19 @@ //// } //// /*classThatHasAlreadyImplementedAnotherClassMethodAfterMethod*/ ////} +////class D1 extends B { +//// /*classThatHasDifferentMethodThanBase*/ +//// getValue1() { +//// return 10; +//// } +//// /*classThatHasDifferentMethodThanBaseAfterMethod*/ +////} +////class D2 extends B { +//// /*classThatHasAlreadyImplementedAnotherClassProtectedMethod*/ +//// protectedMethod() { +//// } +//// /*classThatHasDifferentMethodThanBaseAfterProtectedMethod*/ +////} ////class E { //// /*classThatDoesNotExtendAnotherClass*/ ////} @@ -131,6 +144,8 @@ function filterCompletionInfo(fn: (a: CompletionInfo) => boolean): CompletionInf const instanceMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue" || a === "protectedMethod"); const staticMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "staticMethod"); +const instanceWithoutProtectedMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue"); +const instanceWithoutPublicMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "protectedMethod"); // Not a class element declaration location const nonClassElementMarkers = [ @@ -156,8 +171,8 @@ verifyClassElementLocations({ validMembers: [], invalidMembers: allMembersOfBase // Instance base members and class member keywords allowed const classInstanceElementLocations = [ "classThatIsEmptyAndExtendingAnotherClass", - "classThatHasAlreadyImplementedAnotherClassMethod", - "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", + "classThatHasDifferentMethodThanBase", + "classThatHasDifferentMethodThanBaseAfterMethod", "classThatHasWrittenPublicKeyword", "classThatStartedWritingIdentifier", "propDeclarationWithoutSemicolon", @@ -183,4 +198,16 @@ const staticClassLocations = [ "classElementContainingStatic", "classThatStartedWritingIdentifierAfterStaticModifier" ]; -verifyClassElementLocations(staticMemberInfo, staticClassLocations); \ No newline at end of file +verifyClassElementLocations(staticMemberInfo, staticClassLocations); + +const classInstanceElementWithoutPublicMethodLocations = [ + "classThatHasAlreadyImplementedAnotherClassMethod", + "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", +]; +verifyClassElementLocations(instanceWithoutPublicMemberInfo, classInstanceElementWithoutPublicMethodLocations); + +const classInstanceElementWithoutProtectedMethodLocations = [ + "classThatHasAlreadyImplementedAnotherClassProtectedMethod", + "classThatHasDifferentMethodThanBaseAfterProtectedMethod", +]; +verifyClassElementLocations(instanceWithoutProtectedMemberInfo, classInstanceElementWithoutProtectedMethodLocations); \ No newline at end of file From d6fa91edcd1cf3bf277958881dc1e5f81e8a183a Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 11 May 2017 15:48:17 -0700 Subject: [PATCH 166/282] goToDefinition: Skip default and `=` imports --- src/services/goToDefinition.ts | 39 ++++++++++++------- .../cases/fourslash/goToDefinitionImports.ts | 26 +++++++++++++ 2 files changed, 51 insertions(+), 14 deletions(-) create mode 100644 tests/cases/fourslash/goToDefinitionImports.ts diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 07b1e4448bd..946924bcf87 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -50,20 +50,8 @@ namespace ts.GoToDefinition { // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & SymbolFlags.Alias) { - const declaration = symbol.declarations[0]; - - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === SyntaxKind.Identifier && - (node.parent === declaration || - (declaration.kind === SyntaxKind.ImportSpecifier && declaration.parent && declaration.parent.kind === SyntaxKind.NamedImports))) { - - symbol = typeChecker.getAliasedSymbol(symbol); - } + if (symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) { + symbol = typeChecker.getAliasedSymbol(symbol); } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -136,6 +124,29 @@ namespace ts.GoToDefinition { return getDefinitionFromSymbol(typeChecker, type.symbol, node); } + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node: Node, declaration: Node): boolean { + if (node.kind !== SyntaxKind.Identifier) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case SyntaxKind.ImportClause: + case SyntaxKind.ImportEqualsDeclaration: + return true; + case SyntaxKind.ImportSpecifier: + return declaration.parent.kind === SyntaxKind.NamedImports; + default: + return false; + } + } + function getDefinitionFromSymbol(typeChecker: TypeChecker, symbol: Symbol, node: Node): DefinitionInfo[] { const result: DefinitionInfo[] = []; const declarations = symbol.getDeclarations(); diff --git a/tests/cases/fourslash/goToDefinitionImports.ts b/tests/cases/fourslash/goToDefinitionImports.ts new file mode 100644 index 00000000000..4fdaedb5c3d --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionImports.ts @@ -0,0 +1,26 @@ +/// + +// @Filename: /a.ts +////export default function /*fDef*/f() {} +////export const /*xDef*/x = 0; + +// @Filename: /b.ts +/////*bDef*/declare const b: number; +////export = b; + +// @Filename: /b.ts +////import f, { x } from "./a"; +////import * as /*aDef*/a from "./a"; +////import b = require("./b"); +/////*fUse*/f; +/////*xUse*/x; +/////*aUse*/a; +/////*bUse*/b; + +verify.goToDefinition({ + aUse: "aDef", // Namespace import isn't "skipped" + fUse: "fDef", + xUse: "xDef", + bUse: "bDef", +}); + From 3521b9c54692ee6147b778c861e25127eca25ef6 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Thu, 11 May 2017 16:22:54 -0700 Subject: [PATCH 167/282] if a JSSpecialPropertyDeclaration has a JSDoc type, use it --- src/compiler/checker.ts | 28 ++++++++++++------- .../baselines/reference/checkJsFiles7.symbols | 20 +++++++++++++ tests/baselines/reference/checkJsFiles7.types | 25 +++++++++++++++++ tests/cases/compiler/checkJsFiles7.ts | 12 ++++++++ 4 files changed, 75 insertions(+), 10 deletions(-) create mode 100644 tests/baselines/reference/checkJsFiles7.symbols create mode 100644 tests/baselines/reference/checkJsFiles7.types create mode 100644 tests/cases/compiler/checkJsFiles7.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dde60c19f4e..64a4095162b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4158,6 +4158,7 @@ namespace ts { const types: Type[] = []; let definedInConstructor = false; let definedInMethod = false; + let jsDocType: Type; for (const declaration of symbol.declarations) { const expression = declaration.kind === SyntaxKind.BinaryExpression ? declaration : declaration.kind === SyntaxKind.PropertyAccessExpression ? getAncestor(declaration, SyntaxKind.BinaryExpression) : @@ -4176,19 +4177,26 @@ namespace ts { } } - if (expression.flags & NodeFlags.JavaScriptFile) { - // If there is a JSDoc type, use it - const type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + const type = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type) { + const declarationType = getWidenedType(type); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + const name = getNameOfDeclaration(declaration); + error(name, Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + const type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if @@ -13229,7 +13237,7 @@ namespace ts { } return result; } - } + } function isValidSpreadType(type: Type): boolean { return !!(type.flags & (TypeFlags.Any | TypeFlags.Null | TypeFlags.Undefined | TypeFlags.NonPrimitive) || diff --git a/tests/baselines/reference/checkJsFiles7.symbols b/tests/baselines/reference/checkJsFiles7.symbols new file mode 100644 index 00000000000..a8214483b86 --- /dev/null +++ b/tests/baselines/reference/checkJsFiles7.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/a.js === +class C { +>C : Symbol(C, Decl(a.js, 0, 0)) + + constructor() { + /** @type {boolean} */ + this.a = true; +>this.a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this : Symbol(C, Decl(a.js, 0, 0)) +>a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) + + this.a = !!this.a; +>this.a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this : Symbol(C, Decl(a.js, 0, 0)) +>a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this.a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) +>this : Symbol(C, Decl(a.js, 0, 0)) +>a : Symbol(C.a, Decl(a.js, 1, 16), Decl(a.js, 3, 16)) + } +} diff --git a/tests/baselines/reference/checkJsFiles7.types b/tests/baselines/reference/checkJsFiles7.types new file mode 100644 index 00000000000..a86767b5e44 --- /dev/null +++ b/tests/baselines/reference/checkJsFiles7.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/a.js === +class C { +>C : C + + constructor() { + /** @type {boolean} */ + this.a = true; +>this.a = true : true +>this.a : boolean +>this : this +>a : boolean +>true : true + + this.a = !!this.a; +>this.a = !!this.a : boolean +>this.a : boolean +>this : this +>a : boolean +>!!this.a : boolean +>!this.a : boolean +>this.a : true +>this : this +>a : true + } +} diff --git a/tests/cases/compiler/checkJsFiles7.ts b/tests/cases/compiler/checkJsFiles7.ts new file mode 100644 index 00000000000..2c3d528da00 --- /dev/null +++ b/tests/cases/compiler/checkJsFiles7.ts @@ -0,0 +1,12 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @fileName: a.js +class C { + constructor() { + /** @type {boolean} */ + this.a = true; + this.a = !!this.a; + } +} \ No newline at end of file From 181ff8615064edeb5fdf33121973c1d0ec07dc50 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Thu, 11 May 2017 16:30:43 -0700 Subject: [PATCH 168/282] getApparentType for each constituent of props type of the targetAttributesType --- src/compiler/checker.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 861279b2225..ce89fb72b52 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13548,6 +13548,17 @@ namespace ts { return _jsxElementChildrenPropertyName; } + function createIntersectionOfApparentTypeOfJsxPropsType(propsType: Type): Type { + if (propsType && propsType.flags & TypeFlags.Intersection) { + const propsApprentType: Type[] = []; + for (const t of (propsType).types) { + propsApprentType.push(getApparentType(t)); + } + return getIntersectionType(propsApprentType); + } + return propsType; + } + /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -13568,6 +13579,7 @@ namespace ts { if (callSignature !== unknownSignature) { const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = createIntersectionOfApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -13605,7 +13617,8 @@ namespace ts { let allMatchingAttributesType: Type; for (const candidate of candidatesOutArray) { const callReturnType = getReturnTypeOfSignature(candidate); - const paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + let paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = createIntersectionOfApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { let shouldBeCandidate = true; for (const attribute of openingLikeElement.attributes.properties) { From bce7ddb5c555725e7b3a23d9042d194fca86e82b Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Thu, 11 May 2017 16:30:56 -0700 Subject: [PATCH 169/282] Add tests and update lib tests file --- .../jsx/tsxGenericAttributesType1.tsx | 18 ++++++++++++++++++ .../jsx/tsxGenericAttributesType2.tsx | 10 ++++++++++ .../jsx/tsxGenericAttributesType3.tsx | 17 +++++++++++++++++ .../jsx/tsxGenericAttributesType4.tsx | 18 ++++++++++++++++++ tests/lib/react.d.ts | 2 +- 5 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType1.tsx create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType2.tsx create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType3.tsx create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType4.tsx diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType1.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType1.tsx new file mode 100644 index 00000000000..e6b7fc18ef7 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType1.tsx @@ -0,0 +1,18 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType2.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType2.tsx new file mode 100644 index 00000000000..48acd55546f --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType2.tsx @@ -0,0 +1,10 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType3.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType3.tsx new file mode 100644 index 00000000000..b683c5e7970 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType3.tsx @@ -0,0 +1,17 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + render() { + return ; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType4.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType4.tsx new file mode 100644 index 00000000000..b207f2b4398 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType4.tsx @@ -0,0 +1,18 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} \ No newline at end of file diff --git a/tests/lib/react.d.ts b/tests/lib/react.d.ts index 1d7b787b999..7f03899eb6c 100644 --- a/tests/lib/react.d.ts +++ b/tests/lib/react.d.ts @@ -197,7 +197,7 @@ declare namespace __React { type SFC

= StatelessComponent

; interface StatelessComponent

{ - (props: P, context?: any): ReactElement; + (props: P & { children?: ReactNode }, context?: any): ReactElement; propTypes?: ValidationMap

; contextTypes?: ValidationMap; defaultProps?: P; From 705771d8746aaf5eee67883a1d282776d54dc183 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Thu, 11 May 2017 16:31:40 -0700 Subject: [PATCH 170/282] Update baselines --- .../reference/tsxGenericAttributesType1.js | 28 +++++++ .../tsxGenericAttributesType1.symbols | 66 ++++++++++++++++ .../reference/tsxGenericAttributesType1.types | 77 +++++++++++++++++++ .../tsxGenericAttributesType2.errors.txt | 11 +++ .../reference/tsxGenericAttributesType2.js | 14 ++++ .../reference/tsxGenericAttributesType3.js | 48 ++++++++++++ .../tsxGenericAttributesType3.symbols | 41 ++++++++++ .../reference/tsxGenericAttributesType3.types | 43 +++++++++++ .../tsxGenericAttributesType4.errors.txt | 19 +++++ .../reference/tsxGenericAttributesType4.js | 50 ++++++++++++ 10 files changed, 397 insertions(+) create mode 100644 tests/baselines/reference/tsxGenericAttributesType1.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType1.symbols create mode 100644 tests/baselines/reference/tsxGenericAttributesType1.types create mode 100644 tests/baselines/reference/tsxGenericAttributesType2.errors.txt create mode 100644 tests/baselines/reference/tsxGenericAttributesType2.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType3.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType3.symbols create mode 100644 tests/baselines/reference/tsxGenericAttributesType3.types create mode 100644 tests/baselines/reference/tsxGenericAttributesType4.errors.txt create mode 100644 tests/baselines/reference/tsxGenericAttributesType4.js diff --git a/tests/baselines/reference/tsxGenericAttributesType1.js b/tests/baselines/reference/tsxGenericAttributesType1.js new file mode 100644 index 00000000000..5d3d388396a --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType1.js @@ -0,0 +1,28 @@ +//// [file.tsx] +import React = require('react'); + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator = function (Component) { + return function (props) { return ; }; +}; +var decorator2 = function (Component) { + return function (props) { return ; }; +}; +var decorator3 = function (Component) { + return function (props) { return ; }; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType1.symbols b/tests/baselines/reference/tsxGenericAttributesType1.symbols new file mode 100644 index 00000000000..473de9b5c72 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType1.symbols @@ -0,0 +1,66 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator : Symbol(decorator, Decl(file.tsx, 2, 5)) +>T : Symbol(T, Decl(file.tsx, 2, 28)) +>Component : Symbol(Component, Decl(file.tsx, 2, 31)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 2, 28)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 2, 28)) + + return (props) => +>props : Symbol(props, Decl(file.tsx, 3, 12)) +>Component : Symbol(Component, Decl(file.tsx, 2, 31)) +>props : Symbol(props, Decl(file.tsx, 3, 12)) +>Component : Symbol(Component, Decl(file.tsx, 2, 31)) + +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator2 : Symbol(decorator2, Decl(file.tsx, 6, 5)) +>T : Symbol(T, Decl(file.tsx, 6, 29)) +>x : Symbol(x, Decl(file.tsx, 6, 40)) +>Component : Symbol(Component, Decl(file.tsx, 6, 54)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 6, 29)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 6, 29)) + + return (props) => +>props : Symbol(props, Decl(file.tsx, 7, 12)) +>Component : Symbol(Component, Decl(file.tsx, 6, 54)) +>props : Symbol(props, Decl(file.tsx, 7, 12)) +>x : Symbol(x, Decl(file.tsx, 7, 43)) +>Component : Symbol(Component, Decl(file.tsx, 6, 54)) + +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator3 : Symbol(decorator3, Decl(file.tsx, 10, 5)) +>T : Symbol(T, Decl(file.tsx, 10, 29)) +>x : Symbol(x, Decl(file.tsx, 10, 40)) +>U : Symbol(U, Decl(file.tsx, 10, 53)) +>x : Symbol(x, Decl(file.tsx, 10, 65)) +>Component : Symbol(Component, Decl(file.tsx, 10, 80)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 10, 29)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react.d.ts, 197, 40)) +>T : Symbol(T, Decl(file.tsx, 10, 29)) + + return (props) => +>props : Symbol(props, Decl(file.tsx, 11, 12)) +>Component : Symbol(Component, Decl(file.tsx, 10, 80)) +>x : Symbol(x, Decl(file.tsx, 11, 32)) +>props : Symbol(props, Decl(file.tsx, 11, 12)) +>Component : Symbol(Component, Decl(file.tsx, 10, 80)) + +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType1.types b/tests/baselines/reference/tsxGenericAttributesType1.types new file mode 100644 index 00000000000..50be358302e --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType1.types @@ -0,0 +1,77 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +const decorator = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator : (Component: React.StatelessComponent) => React.StatelessComponent +>function (Component: React.StatelessComponent): React.StatelessComponent { return (props) => } : (Component: React.StatelessComponent) => React.StatelessComponent +>T : T +>Component : React.StatelessComponent +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T + + return (props) => +>(props) => : (props: T & { children?: React.ReactNode; }) => JSX.Element +>props : T & { children?: React.ReactNode; } +> : JSX.Element +>Component : React.StatelessComponent +>props : T & { children?: React.ReactNode; } +>Component : React.StatelessComponent + +}; + +const decorator2 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator2 : (Component: React.StatelessComponent) => React.StatelessComponent +>function (Component: React.StatelessComponent): React.StatelessComponent { return (props) => } : (Component: React.StatelessComponent) => React.StatelessComponent +>T : T +>x : number +>Component : React.StatelessComponent +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T + + return (props) => +>(props) => : (props: T & { children?: React.ReactNode; }) => JSX.Element +>props : T & { children?: React.ReactNode; } +> : JSX.Element +>Component : React.StatelessComponent +>props : T & { children?: React.ReactNode; } +>x : number +>2 : 2 +>Component : React.StatelessComponent + +}; + +const decorator3 = function (Component: React.StatelessComponent): React.StatelessComponent { +>decorator3 : (Component: React.StatelessComponent) => React.StatelessComponent +>function (Component: React.StatelessComponent): React.StatelessComponent { return (props) => } : (Component: React.StatelessComponent) => React.StatelessComponent +>T : T +>x : number +>U : U +>x : number +>Component : React.StatelessComponent +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T +>React : any +>StatelessComponent : React.StatelessComponent

+>T : T + + return (props) => +>(props) => : (props: T & { children?: React.ReactNode; }) => JSX.Element +>props : T & { children?: React.ReactNode; } +> : JSX.Element +>Component : React.StatelessComponent +>x : number +>2 : 2 +>props : T & { children?: React.ReactNode; } +>Component : React.StatelessComponent + +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType2.errors.txt b/tests/baselines/reference/tsxGenericAttributesType2.errors.txt new file mode 100644 index 00000000000..cbd926c9b69 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType2.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/jsx/file.tsx(4,45): error TS2339: Property 'y' does not exist on type 'IntrinsicAttributes & { x: number; } & { children?: ReactNode; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => + ~~~~~~~~~~ +!!! error TS2339: Property 'y' does not exist on type 'IntrinsicAttributes & { x: number; } & { children?: ReactNode; }'. + }; \ No newline at end of file diff --git a/tests/baselines/reference/tsxGenericAttributesType2.js b/tests/baselines/reference/tsxGenericAttributesType2.js new file mode 100644 index 00000000000..7b46d08c2c4 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType2.js @@ -0,0 +1,14 @@ +//// [file.tsx] +import React = require('react'); + +const decorator4 = function (Component: React.StatelessComponent): React.StatelessComponent { + return (props) => +}; + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator4 = function (Component) { + return function (props) { return ; }; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType3.js b/tests/baselines/reference/tsxGenericAttributesType3.js new file mode 100644 index 00000000000..51491d99aa2 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType3.js @@ -0,0 +1,48 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return

hi
; + } +} +class B extends React.Component { + render() { + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + return ; + }; + return B; +}(React.Component)); diff --git a/tests/baselines/reference/tsxGenericAttributesType3.symbols b/tests/baselines/reference/tsxGenericAttributesType3.symbols new file mode 100644 index 00000000000..8c235257e8d --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType3.symbols @@ -0,0 +1,41 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +class B1 extends React.Component { +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) +>x : Symbol(x, Decl(file.tsx, 2, 20)) +>x : Symbol(x, Decl(file.tsx, 2, 36)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) + + render() { +>render : Symbol(B1.render, Decl(file.tsx, 2, 82)) + + return
hi
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + } +} +class B extends React.Component { +>B : Symbol(B, Decl(file.tsx, 6, 1)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) + + render() { +>render : Symbol(B.render, Decl(file.tsx, 7, 43)) + + return ; +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(B, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>x : Symbol(x, Decl(file.tsx, 9, 34)) + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType3.types b/tests/baselines/reference/tsxGenericAttributesType3.types new file mode 100644 index 00000000000..72674ac5bf7 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType3.types @@ -0,0 +1,43 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +class B1 extends React.Component { +>B1 : B1 +>T : T +>x : string +>x : string +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>T : T + + render() { +>render : () => JSX.Element + + return
hi
; +>
hi
: JSX.Element +>div : any +>div : any + } +} +class B extends React.Component { +>B : B +>U : U +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>U : U + + render() { +>render : () => JSX.Element + + return ; +> : JSX.Element +>B1 : typeof B1 +>this.props : U & { children?: React.ReactNode; } +>this : this +>props : U & { children?: React.ReactNode; } +>x : string + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType4.errors.txt b/tests/baselines/reference/tsxGenericAttributesType4.errors.txt new file mode 100644 index 00000000000..ee91f938b9f --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType4.errors.txt @@ -0,0 +1,19 @@ +tests/cases/conformance/jsx/file.tsx(11,36): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + class B1 extends React.Component { + render() { + return
hi
; + } + } + class B extends React.Component { + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + ~~~~~~ +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxGenericAttributesType4.js b/tests/baselines/reference/tsxGenericAttributesType4.js new file mode 100644 index 00000000000..a00d03cd61b --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType4.js @@ -0,0 +1,50 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + }; + return B; +}(React.Component)); From a5e93c427ba9f1987b8b84f31a20deb1af5bf35e Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 11 May 2017 16:40:14 -0700 Subject: [PATCH 171/282] remove souceFile checks --- src/compiler/checker.ts | 4 ++-- src/compiler/emitter.ts | 17 +++++++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ed5c7ea669e..2e45a17a207 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2289,9 +2289,9 @@ namespace ts { const newLine = NewLineKind.None; const options = { newLine, removeComments: true }; const writer = createTextWriter(""); - // writer.writeLine = noop; const printer = createPrinter(options, writer); - printer.writeNode(EmitHint.Unspecified, typeNode, /*sourceFile*/ undefined, writer); + const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(EmitHint.Unspecified, typeNode, /*sourceFile*/ sourceFile, writer); const result = writer.getText(); const maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index b96e87ec55c..073c49df559 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -153,7 +153,7 @@ namespace ts { for (let i = 0; i < numNodes; i++) { const currentNode = bundle ? bundle.sourceFiles[i] : node; const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile; - const shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && getExternalHelpersModuleName(sourceFile) !== undefined); + const shouldSkip = compilerOptions.noEmitHelpers || getExternalHelpersModuleName(sourceFile) !== undefined; const shouldBundle = isSourceFile(currentNode) && !isOwnFileEmit; const helpers = getEmitHelpers(currentNode); if (helpers) { @@ -234,6 +234,11 @@ namespace ts { writeBundle }; + /** + * If `sourceFile` is `undefined`, `node` must be a synthesized `TypeNode`. + */ + function printNode(hint: EmitHint, node: TypeNode, sourceFile: undefined): string; + function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined): string { switch (hint) { case EmitHint.SourceFile: @@ -1112,7 +1117,7 @@ namespace ts { function emitPropertyAccessExpression(node: PropertyAccessExpression) { let indentBeforeDot = false; let indentAfterDot = false; - if (currentSourceFile && !(getEmitFlags(node) & EmitFlags.NoIndentation)) { + if (!(getEmitFlags(node) & EmitFlags.NoIndentation)) { const dotRangeStart = node.expression.end; const dotRangeEnd = skipTrivia(currentSourceFile.text, node.expression.end) + 1; const dotToken = { kind: SyntaxKind.DotToken, pos: dotRangeStart, end: dotRangeEnd }; @@ -2520,7 +2525,7 @@ namespace ts { const firstChild = children[0]; if (firstChild === undefined) { - return !(currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile)); + return !(rangeIsOnSingleLine(parentNode, currentSourceFile)); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(firstChild)) { return synthesizedNodeStartsOnNewLine(firstChild, format); @@ -2546,7 +2551,7 @@ namespace ts { return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); } else { - return !(currentSourceFile && rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile)); + return !(rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile)); } } else { @@ -2565,13 +2570,13 @@ namespace ts { const lastChild = lastOrUndefined(children); if (lastChild === undefined) { - return !(currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile)); + return !(rangeIsOnSingleLine(parentNode, currentSourceFile)); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(lastChild)) { return synthesizedNodeStartsOnNewLine(lastChild, format); } else { - return !(currentSourceFile && rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile)); + return !(rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile)); } } else { From 82109d3d1c1f4d31bad310521e5375875e2db4e0 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 11 May 2017 17:39:27 -0700 Subject: [PATCH 172/282] cleanup --- src/compiler/checker.ts | 61 ++++++++++++----------------------------- 1 file changed, 17 insertions(+), 44 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2e45a17a207..f6930b01aca 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2229,19 +2229,7 @@ namespace ts { return result; } - function oldTypeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - const writer = getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - let result = writer.string(); - releaseStringWriter(writer); - - const maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; - if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; - } - return result; - } - + function typeFormatFlagsToNodeBuilderFlags(flags: TypeFormatFlags): NodeBuilderFlags { let result = NodeBuilderFlags.None; if (flags & TypeFormatFlags.WriteArrayAsGenericType) { @@ -2282,8 +2270,6 @@ namespace ts { } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - const str = oldTypeToString(type, enclosingDeclaration, flags); str; - const str2 = oldTypeToString(type, enclosingDeclaration, flags); str2; const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, typeFormatFlagsToNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors, !!(flags & TypeFormatFlags.InTypeAlias)); Debug.assert(typeNode !== undefined, "should always get typenode?"); const newLine = NewLineKind.None; @@ -2331,11 +2317,8 @@ namespace ts { // State encounteredError: boolean; inObjectTypeLiteral: boolean; - // TODO: needed for part of parens handling InElementType: boolean; // Writing an array or union element type - // TODO: ??? - InFirstTypeArgument: boolean; // Writing first type argument of the instantiated type - // TODO: ??? + InFirstTypeArgument: boolean; // Writing first type argument of the instantiated type InTypeAlias: boolean; // Writing type in type alias declaration symbolStack: Symbol[] | undefined; } @@ -2354,18 +2337,15 @@ namespace ts { } function typeToTypeNodeHelper(type: Type, context: NodeBuilderContext): TypeNode { - const InElementType = context.InElementType; - // TODO: why doesn't tts unset the flag? + const inElementType = context.InElementType; context.InElementType = false; const inTypeAlias = context.InTypeAlias; context.InTypeAlias = false; const inFirstTypeArgument = context.InFirstTypeArgument; context.InFirstTypeArgument = false; - // TODO: should be assert? if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } @@ -2382,7 +2362,7 @@ namespace ts { return createKeywordTypeNode(SyntaxKind.BooleanKeyword); } if (type.flags & TypeFlags.Enum) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (TypeFlags.StringLiteral)) { @@ -2396,7 +2376,7 @@ namespace ts { } if (type.flags & TypeFlags.EnumLiteral) { const parentSymbol = getParentOfSymbol(type.symbol); - const parentName = symbolToName(parentSymbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); + const parentName = symbolToName(parentSymbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); const name = getNameOfSymbol(type.symbol, context); const enumLiteralName = createQualifiedName(parentName, name); return createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); @@ -2436,12 +2416,11 @@ namespace ts { } if (objectFlags & ObjectFlags.ClassOrInterface) { Debug.assert(!!(type.flags & TypeFlags.Object)); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); - // TODO(aozgaa): handle type arguments. + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & TypeFlags.TypeParameter) { - const name = symbolToName(type.symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context); + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -2451,7 +2430,6 @@ namespace ts { const name = symbolToTypeReferenceName(type.aliasSymbol); const typeArgumentNodes = toTypeArgumentNodes(type.aliasTypeArguments, context); return createTypeReferenceNode(name, typeArgumentNodes); - // return symbolToTypeReferenceIdentifier(type.aliasSymbol, type.aliasTypeArguments); } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { @@ -2459,7 +2437,7 @@ namespace ts { const typeNodes = types && mapToTypeNodeArray(types, context, /*addInElementTypeFlag*/ true, /*addInFirstTypeArgumentFlag*/ false); if (typeNodes && typeNodes.length > 0) { const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); - return InElementType ? createParenthesizedTypeNode(unionOrIntersectionTypeNode) : unionOrIntersectionTypeNode; + return inElementType ? createParenthesizedTypeNode(unionOrIntersectionTypeNode) : unionOrIntersectionTypeNode; } else { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyUnionOrIntersection)) { @@ -2521,7 +2499,7 @@ namespace ts { const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - const entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false, SymbolFlags.Type, context); + const entityName = symbolToName(typeAlias, context, SymbolFlags.Type, /*expectsIdentifier*/ false ); return createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -2598,7 +2576,7 @@ namespace ts { } function shouldAddParenthesisAroundFunctionType(callSignature: Signature, context: NodeBuilderContext) { - if (InElementType) { + if (inElementType) { return true; } else if (inFirstTypeArgument) { @@ -2611,14 +2589,13 @@ namespace ts { } function createTypeQueryNodeFromSymbol(symbol: Symbol, symbolFlags: SymbolFlags) { - const entityName = symbolToName(symbol, /*expectsIdentifier*/ false, symbolFlags, context); + const entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return createTypeQueryNode(entityName); } function symbolToTypeReferenceName(symbol: Symbol) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display - const entityName = symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.name) ? symbolToName(symbol, /*expectsIdentifier*/ false, SymbolFlags.Type, context) : createIdentifier(""); - // TODO: assert no type args? + const entityName = symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false) : createIdentifier(""); return entityName; } @@ -2651,7 +2628,6 @@ namespace ts { let i = 0; let qualifiedName: QualifiedName | undefined; if (outerTypeParameters) { - let inFirstTypeArgument = true; const length = outerTypeParameters.length; while (i < length) { // Find group of type arguments for type parameters with the same declaring container. @@ -2676,7 +2652,6 @@ namespace ts { qualifiedName = createQualifiedName(namePart, /*right*/ undefined); } } - inFirstTypeArgument = false; } } @@ -2745,12 +2720,11 @@ namespace ts { return typeElements; } - // TODO: make logic mirror that of writeObjectLiteralType for (const propertySymbol of properties) { const propertyType = getTypeOfSymbol(propertySymbol); const saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - const propertyName = symbolToName(propertySymbol, /*expectsIdentifier*/ true, SymbolFlags.Value, context); + const propertyName = symbolToName(propertySymbol, context, SymbolFlags.Value, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? createToken(SyntaxKind.QuestionToken) : undefined; if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length) { @@ -2856,7 +2830,7 @@ namespace ts { const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); const defaultParameter = getDefaultFromTypeParameter(type); const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - const name = symbolToName(type.symbol, /*expectsIdentifier*/ true, SymbolFlags.Type, context); + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ true); return createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } @@ -2903,10 +2877,9 @@ namespace ts { } } - // TODO: add SymbolFormatFlags?? Yes to add outer type parameters. Defer UseOnlyExternalAliasing until a separate symbolbuilder PR. - function symbolToName(symbol: Symbol, expectsIdentifier: true, meaning: SymbolFlags, context: NodeBuilderContext): Identifier; - function symbolToName(symbol: Symbol, expectsIdentifier: false, meaning: SymbolFlags, context: NodeBuilderContext): EntityName; - function symbolToName(symbol: Symbol, expectsIdentifier: boolean, meaning: SymbolFlags, context: NodeBuilderContext): EntityName { + function symbolToName(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, expectsIdentifier: true): Identifier; + function symbolToName(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, expectsIdentifier: false): EntityName; + function symbolToName(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, expectsIdentifier: boolean): EntityName { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; From c099938f61291e777fb796af20dff13eb3de1e10 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 11 May 2017 18:18:35 -0700 Subject: [PATCH 173/282] move state to flags --- src/compiler/checker.ts | 61 ++++++++++++++++++----------------------- src/compiler/types.ts | 8 ++++++ 2 files changed, 35 insertions(+), 34 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f6930b01aca..b5000a7af99 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2229,7 +2229,7 @@ namespace ts { return result; } - + function typeFormatFlagsToNodeBuilderFlags(flags: TypeFormatFlags): NodeBuilderFlags { let result = NodeBuilderFlags.None; if (flags & TypeFormatFlags.WriteArrayAsGenericType) { @@ -2270,7 +2270,7 @@ namespace ts { } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, typeFormatFlagsToNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors, !!(flags & TypeFormatFlags.InTypeAlias)); + const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, typeFormatFlagsToNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors); Debug.assert(typeNode !== undefined, "should always get typenode?"); const newLine = NewLineKind.None; const options = { newLine, removeComments: true }; @@ -2289,9 +2289,8 @@ namespace ts { function createNodeBuilder() { return { - typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, inTypeAlias?: boolean) => { + typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => { const context = createNodeBuilderContext(enclosingDeclaration, flags); - context.InTypeAlias = inTypeAlias; const resultingNode = typeToTypeNodeHelper(type, context); const result = context.encounteredError ? undefined : resultingNode; return result; @@ -2312,14 +2311,10 @@ namespace ts { interface NodeBuilderContext { enclosingDeclaration: Node | undefined; - readonly flags: NodeBuilderFlags | undefined; + flags: NodeBuilderFlags | undefined; // State encounteredError: boolean; - inObjectTypeLiteral: boolean; - InElementType: boolean; // Writing an array or union element type - InFirstTypeArgument: boolean; // Writing first type argument of the instantiated type - InTypeAlias: boolean; // Writing type in type alias declaration symbolStack: Symbol[] | undefined; } @@ -2328,21 +2323,15 @@ namespace ts { enclosingDeclaration, flags, encounteredError: false, - inObjectTypeLiteral: false, - InElementType: false, - InFirstTypeArgument: false, - InTypeAlias: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type: Type, context: NodeBuilderContext): TypeNode { - const inElementType = context.InElementType; - context.InElementType = false; - const inTypeAlias = context.InTypeAlias; - context.InTypeAlias = false; - const inFirstTypeArgument = context.InFirstTypeArgument; - context.InFirstTypeArgument = false; + const inElementType = context.flags & NodeBuilderFlags.InElementType; + const inFirstTypeArgument = context.flags & NodeBuilderFlags.InFirstTypeArgument; + const inTypeAlias = context.flags & NodeBuilderFlags.InTypeAlias; + context.flags &= ~(NodeBuilderFlags.StateClearingFlags); if (!type) { context.encounteredError = true; @@ -2400,7 +2389,7 @@ namespace ts { return createKeywordTypeNode(SyntaxKind.ObjectKeyword); } if (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType) { - if (context.inObjectTypeLiteral) { + if (context.flags & NodeBuilderFlags.inObjectTypeLiteral) { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowThisInObjectLiteral)) { context.encounteredError = true; } @@ -2455,16 +2444,16 @@ namespace ts { if (type.flags & TypeFlags.Index) { const indexedType = (type).type; - context.InElementType = true; + context.flags |= NodeBuilderFlags.InElementType; const indexTypeNode = typeToTypeNodeHelper(indexedType, context); - Debug.assert(context.InElementType === false); + Debug.assert(!(context.flags & NodeBuilderFlags.InElementType)); return createTypeOperatorNode(indexTypeNode); } if (type.flags & TypeFlags.IndexedAccess) { - context.InElementType = true; + context.flags |= NodeBuilderFlags.InElementType; const objectTypeNode = typeToTypeNodeHelper((type).objectType, context); - Debug.assert(context.InElementType === false); + Debug.assert(!(context.flags & NodeBuilderFlags.InElementType)); const indexTypeNode = typeToTypeNodeHelper((type).indexType, context); return createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } @@ -2567,10 +2556,10 @@ namespace ts { } } - const saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + const savedFlags = context.flags; + context.flags |= NodeBuilderFlags.inObjectTypeLiteral; const members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; + context.flags = savedFlags; const typeLiteralNode = createTypeLiteralNode(members); return setEmitFlags(typeLiteralNode, EmitFlags.ToStringFormatting); } @@ -2606,9 +2595,11 @@ namespace ts { const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return createTypeReferenceNode("Array", [typeArgumentNode]); } - context.InElementType = true; + + context.flags |= NodeBuilderFlags.InElementType; const elementType = typeToTypeNodeHelper(typeArguments[0], context); - context.InElementType = false; + Debug.assert(!(context.flags & NodeBuilderFlags.InElementType)); + return createArrayTypeNode(elementType); } else if (type.target.objectFlags & ObjectFlags.Tuple) { @@ -2756,19 +2747,21 @@ namespace ts { function mapToTypeNodeArray(types: Type[], context: NodeBuilderContext, addInElementTypeFlag: boolean, addInFirstTypeArgumentFlag: boolean): TypeNode[] { const result = []; - Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); + Debug.assert(!(context.flags & NodeBuilderFlags.InElementType), "should be unset at the beginning of the helper"); for (let i = 0; i < types.length; ++i) { const type = types[i]; - context.InElementType = addInElementTypeFlag; - if (i === 0) { - context.InFirstTypeArgument = addInFirstTypeArgumentFlag; + if (addInElementTypeFlag) { + context.flags |= NodeBuilderFlags.InElementType; + } + if (i === 0 && addInFirstTypeArgumentFlag) { + context.flags |= NodeBuilderFlags.InFirstTypeArgument; } const typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); } } - Debug.assert(context.InElementType === false, "should be unset at the beginning of the helper"); + Debug.assert(!(context.flags & NodeBuilderFlags.InElementType), "should be unset at the end of the helper"); return result; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 73d6067cb10..e23bba7b238 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2589,6 +2589,14 @@ namespace ts { ignoreErrors = allowThisInObjectLiteral | allowQualifedNameInPlaceOfIdentifier | allowTypeParameterInQualifiedName | allowAnonymousIdentifier | allowEmptyUnionOrIntersection | allowEmptyTuple, + // State + inObjectTypeLiteral = 1 << 20, + InElementType = 1 << 21, // Writing an array or union element type + InFirstTypeArgument = 1 << 22, // Writing first type argument of the instantiated type + InTypeAlias = 1 << 23, // Writing type in type alias declaration + + /** Flags that should not be passed on to sub-nodes of the current node being built. */ + StateClearingFlags = InElementType | InFirstTypeArgument | InTypeAlias } export interface SymbolDisplayBuilder { From 0432257949b617e043bbc45f7bab2a1ba24eadd9 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 11 May 2017 18:39:40 -0700 Subject: [PATCH 174/282] use EmitFlags.SingleLine --- src/compiler/checker.ts | 4 ++-- src/compiler/emitter.ts | 4 ++-- src/compiler/types.ts | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b5000a7af99..a5e1787cfd0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2561,7 +2561,7 @@ namespace ts { const members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; const typeLiteralNode = createTypeLiteralNode(members); - return setEmitFlags(typeLiteralNode, EmitFlags.ToStringFormatting); + return setEmitFlags(typeLiteralNode, EmitFlags.SingleLine); } function shouldAddParenthesisAroundFunctionType(callSignature: Signature, context: NodeBuilderContext) { @@ -2865,7 +2865,7 @@ namespace ts { if (clone.kind === SyntaxKind.BindingElement) { (clone).initializer = undefined; } - return setEmitFlags(clone, EmitFlags.ToStringFormatting); + return setEmitFlags(clone, EmitFlags.SingleLine); } } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 073c49df559..59e3c9df96c 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -962,7 +962,7 @@ namespace ts { function emitTypeLiteral(node: TypeLiteralNode) { write("{"); if (node.members.length > 0) { - emitList(node, node.members, getEmitFlags(node) & EmitFlags.ToStringFormatting ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers); + emitList(node, node.members, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers); } write("}"); } @@ -1054,7 +1054,7 @@ namespace ts { } else { write("{"); - emitList(node, elements, getEmitFlags(node) & EmitFlags.ToStringFormatting ? ListFormat.ObjectBindingPatternElements : ListFormat.ObjectBindingPatternElementsWithSpaceBetweenBraces); + emitList(node, elements, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.ObjectBindingPatternElements : ListFormat.ObjectBindingPatternElementsWithSpaceBetweenBraces); write("}"); } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e23bba7b238..9191ad844f7 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3979,7 +3979,6 @@ namespace ts { NoHoisting = 1 << 20, // Do not hoist this declaration in --module system HasEndOfDeclarationMarker = 1 << 21, // Declaration has an associated NotEmittedStatement to mark the end of the declaration Iterator = 1 << 22, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. - ToStringFormatting = 1 << 23 } export interface EmitHelper { From 7d48deec340e5b9d0096fad3b5e8751d7e5b68c3 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 11 May 2017 18:44:26 -0700 Subject: [PATCH 175/282] handle todo --- src/compiler/checker.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a5e1787cfd0..fa81541d517 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2728,7 +2728,6 @@ namespace ts { } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : createKeywordTypeNode(SyntaxKind.AnyKeyword); const modifiers = isReadonlySymbol(propertySymbol) ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined; From 3640abd0a72f4a3018a9014d97df88c7f900d342 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Thu, 11 May 2017 18:53:57 -0700 Subject: [PATCH 176/282] Remove unused flags --- src/compiler/checker.ts | 28 ++++++---------------------- src/compiler/types.ts | 14 +------------- src/compiler/visitor.ts | 1 - 3 files changed, 7 insertions(+), 36 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fa81541d517..729fbdcaa52 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2232,20 +2232,17 @@ namespace ts { function typeFormatFlagsToNodeBuilderFlags(flags: TypeFormatFlags): NodeBuilderFlags { let result = NodeBuilderFlags.None; - if (flags & TypeFormatFlags.WriteArrayAsGenericType) { - result |= NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & TypeFormatFlags.UseTypeOfFunction) { - result |= NodeBuilderFlags.UseTypeOfFunction; + if (flags === TypeFormatFlags.None) { + return result; } if (flags & TypeFormatFlags.NoTruncation) { result |= NodeBuilderFlags.NoTruncation; } - if (flags & TypeFormatFlags.WriteArrowStyleSignature) { - result |= NodeBuilderFlags.WriteArrowStyleSignature; + if (flags & TypeFormatFlags.UseFullyQualifiedType) { + result |= NodeBuilderFlags.UseFullyQualifiedType; } - if (flags & TypeFormatFlags.WriteOwnNameForAnyLike) { - result |= NodeBuilderFlags.WriteOwnNameForAnyLike; + if (flags & TypeFormatFlags.SuppressAnyReturnType) { + result |= NodeBuilderFlags.SuppressAnyReturnType; } if (flags & TypeFormatFlags.WriteArrayAsGenericType) { result |= NodeBuilderFlags.WriteArrayAsGenericType; @@ -2253,18 +2250,6 @@ namespace ts { if (flags & TypeFormatFlags.WriteTypeArgumentsOfSignature) { result |= NodeBuilderFlags.WriteTypeArgumentsOfSignature; } - if (flags & TypeFormatFlags.UseFullyQualifiedType) { - result |= NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & TypeFormatFlags.UseTypeAliasValue) { - result |= NodeBuilderFlags.UseTypeAliasValue; - } - if (flags & TypeFormatFlags.SuppressAnyReturnType) { - result |= NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & TypeFormatFlags.AddUndefined) { - result |= NodeBuilderFlags.AddUndefined; - } return result; } @@ -2893,7 +2878,6 @@ namespace ts { function createEntityNameFromSymbolChain(chain: Symbol[], index: number): EntityName { Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; const symbol = chain[index]; let typeParameterNodes: TypeNode[] | undefined; if (index > 0) { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 9191ad844f7..49f1e9a3382 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2497,7 +2497,7 @@ namespace ts { /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, inTypeAlias?: boolean): TypeNode; + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ @@ -2562,22 +2562,10 @@ namespace ts { None = 0, // Options NoTruncation = 1 << 0, // Don't truncate result - // TODO: part of emit. WriteArrayAsGenericType = 1 << 1, // Write Array instead T[] - // TODO: part of emit. - UseTypeOfFunction = 1 << 2, // Write typeof instead of function type literal - // TODO: part of emit. - WriteArrowStyleSignature = 1 << 3, // Write arrow style signature - // TODO: turn it into a failing type reference? - WriteOwnNameForAnyLike = 1 << 4, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) - // TODO WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) - // TODO - UseTypeAliasValue = 1 << 7, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type. - // TODO - AddUndefined = 1 << 9, // Add undefined to types of initialized, non-optional parameters // Error handling allowThisInObjectLiteral = 1 << 10, diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index fce43b622bb..ce7908b885e 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -359,7 +359,6 @@ namespace ts { case SyntaxKind.PropertySignature: return updatePropertySignature((node), - // TODO: tokenVisitor or visitor for a nodearray of tokens? nodesVisitor((node).modifiers, visitor, isToken), visitNode((node).name, visitor, isPropertyName), visitNode((node).questionToken, tokenVisitor, isToken), From 84f419b533cd3382573320be4b5796a1a0eef144 Mon Sep 17 00:00:00 2001 From: Yui T Date: Thu, 11 May 2017 22:40:21 -0700 Subject: [PATCH 177/282] getApparentType of the propsType --- src/compiler/checker.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ce89fb72b52..03302ec5f32 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13548,13 +13548,16 @@ namespace ts { return _jsxElementChildrenPropertyName; } - function createIntersectionOfApparentTypeOfJsxPropsType(propsType: Type): Type { - if (propsType && propsType.flags & TypeFlags.Intersection) { - const propsApprentType: Type[] = []; - for (const t of (propsType).types) { - propsApprentType.push(getApparentType(t)); + function getApparentTypeOfJsxPropsType(propsType: Type): Type { + if (propsType) { + if (propsType.flags & TypeFlags.Intersection) { + const propsApprentType: Type[] = []; + for (const t of (propsType).types) { + propsApprentType.push(getApparentType(t)); + } + return getIntersectionType(propsApprentType); } - return getIntersectionType(propsApprentType); + return getApparentType(propsType); } return propsType; } @@ -13579,7 +13582,7 @@ namespace ts { if (callSignature !== unknownSignature) { const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); - paramType = createIntersectionOfApparentTypeOfJsxPropsType(paramType); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -13618,7 +13621,7 @@ namespace ts { for (const candidate of candidatesOutArray) { const callReturnType = getReturnTypeOfSignature(candidate); let paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = createIntersectionOfApparentTypeOfJsxPropsType(paramType); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { let shouldBeCandidate = true; for (const attribute of openingLikeElement.attributes.properties) { From 8d09085800f131f0a5e70ed0fd2c8cb81d5afdc5 Mon Sep 17 00:00:00 2001 From: Yui T Date: Thu, 11 May 2017 22:40:34 -0700 Subject: [PATCH 178/282] Add more tests and update baselines --- .../tsxGenericAttributesType5.errors.txt | 20 ++++++++ .../reference/tsxGenericAttributesType5.js | 51 +++++++++++++++++++ .../reference/tsxGenericAttributesType6.js | 49 ++++++++++++++++++ .../tsxGenericAttributesType6.symbols | 45 ++++++++++++++++ .../reference/tsxGenericAttributesType6.types | 47 +++++++++++++++++ .../reference/tsxGenericAttributesType7.js | 22 ++++++++ .../tsxGenericAttributesType7.symbols | 35 +++++++++++++ .../reference/tsxGenericAttributesType7.types | 39 ++++++++++++++ .../reference/tsxGenericAttributesType8.js | 22 ++++++++ .../tsxGenericAttributesType8.symbols | 34 +++++++++++++ .../reference/tsxGenericAttributesType8.types | 38 ++++++++++++++ .../tsxStatelessFunctionComponents3.types | 6 +-- .../jsx/tsxGenericAttributesType5.tsx | 19 +++++++ .../jsx/tsxGenericAttributesType6.tsx | 18 +++++++ .../jsx/tsxGenericAttributesType7.tsx | 15 ++++++ .../jsx/tsxGenericAttributesType8.tsx | 15 ++++++ 16 files changed, 472 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/tsxGenericAttributesType5.errors.txt create mode 100644 tests/baselines/reference/tsxGenericAttributesType5.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType6.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType6.symbols create mode 100644 tests/baselines/reference/tsxGenericAttributesType6.types create mode 100644 tests/baselines/reference/tsxGenericAttributesType7.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType7.symbols create mode 100644 tests/baselines/reference/tsxGenericAttributesType7.types create mode 100644 tests/baselines/reference/tsxGenericAttributesType8.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType8.symbols create mode 100644 tests/baselines/reference/tsxGenericAttributesType8.types create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType5.tsx create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType6.tsx create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType7.tsx create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType8.tsx diff --git a/tests/baselines/reference/tsxGenericAttributesType5.errors.txt b/tests/baselines/reference/tsxGenericAttributesType5.errors.txt new file mode 100644 index 00000000000..83f07326f92 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType5.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/jsx/file.tsx(12,36): error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + class B1 extends React.Component { + render() { + return
hi
; + } + } + class B extends React.Component { + props: U; + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + ~~~~~~ +!!! error TS2339: Property 'x' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { children?: ReactNode; }'. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxGenericAttributesType5.js b/tests/baselines/reference/tsxGenericAttributesType5.js new file mode 100644 index 00000000000..cb535417dd6 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType5.js @@ -0,0 +1,51 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + }; + return B; +}(React.Component)); diff --git a/tests/baselines/reference/tsxGenericAttributesType6.js b/tests/baselines/reference/tsxGenericAttributesType6.js new file mode 100644 index 00000000000..84cab3e1f94 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType6.js @@ -0,0 +1,49 @@ +//// [file.tsx] +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + return ; + } +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var B1 = (function (_super) { + __extends(B1, _super); + function B1() { + return _super !== null && _super.apply(this, arguments) || this; + } + B1.prototype.render = function () { + return
hi
; + }; + return B1; +}(React.Component)); +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + B.prototype.render = function () { + return ; + }; + return B; +}(React.Component)); diff --git a/tests/baselines/reference/tsxGenericAttributesType6.symbols b/tests/baselines/reference/tsxGenericAttributesType6.symbols new file mode 100644 index 00000000000..27c8ed2d6dc --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType6.symbols @@ -0,0 +1,45 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +class B1 extends React.Component { +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) +>x : Symbol(x, Decl(file.tsx, 2, 20)) +>x : Symbol(x, Decl(file.tsx, 2, 36)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>T : Symbol(T, Decl(file.tsx, 2, 9)) + + render() { +>render : Symbol(B1.render, Decl(file.tsx, 2, 82)) + + return
hi
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + } +} +class B extends React.Component { +>B : Symbol(B, Decl(file.tsx, 6, 1)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) + + props: U; +>props : Symbol(B.props, Decl(file.tsx, 7, 43)) +>U : Symbol(U, Decl(file.tsx, 7, 8)) + + render() { +>render : Symbol(B.render, Decl(file.tsx, 8, 13)) + + return ; +>B1 : Symbol(B1, Decl(file.tsx, 0, 32)) +>this.props : Symbol(B.props, Decl(file.tsx, 7, 43)) +>this : Symbol(B, Decl(file.tsx, 6, 1)) +>props : Symbol(B.props, Decl(file.tsx, 7, 43)) +>x : Symbol(x, Decl(file.tsx, 10, 34)) + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType6.types b/tests/baselines/reference/tsxGenericAttributesType6.types new file mode 100644 index 00000000000..662b6299dad --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType6.types @@ -0,0 +1,47 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +class B1 extends React.Component { +>B1 : B1 +>T : T +>x : string +>x : string +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>T : T + + render() { +>render : () => JSX.Element + + return
hi
; +>
hi
: JSX.Element +>div : any +>div : any + } +} +class B extends React.Component { +>B : B +>U : U +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>U : U + + props: U; +>props : U +>U : U + + render() { +>render : () => JSX.Element + + return ; +> : JSX.Element +>B1 : typeof B1 +>this.props : U +>this : this +>props : U +>x : string + } +} diff --git a/tests/baselines/reference/tsxGenericAttributesType7.js b/tests/baselines/reference/tsxGenericAttributesType7.js new file mode 100644 index 00000000000..4e254f25e55 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType7.js @@ -0,0 +1,22 @@ +//// [file.tsx] +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator = function (props) { + return ; +}; +var decorator1 = function (props) { + return ; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType7.symbols b/tests/baselines/reference/tsxGenericAttributesType7.symbols new file mode 100644 index 00000000000..e31042bd843 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType7.symbols @@ -0,0 +1,35 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +declare function Component(props: T) : JSX.Element; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>props : Symbol(props, Decl(file.tsx, 2, 30)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) +>Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) + +const decorator = function (props: U) { +>decorator : Symbol(decorator, Decl(file.tsx, 3, 5)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +} + +const decorator1 = function (props: U) { +>decorator1 : Symbol(decorator1, Decl(file.tsx, 7, 5)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) +>x : Symbol(x, Decl(file.tsx, 7, 40)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +>x : Symbol(x, Decl(file.tsx, 8, 32)) +} diff --git a/tests/baselines/reference/tsxGenericAttributesType7.types b/tests/baselines/reference/tsxGenericAttributesType7.types new file mode 100644 index 00000000000..58d853e4881 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType7.types @@ -0,0 +1,39 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +declare function Component(props: T) : JSX.Element; +>Component : (props: T) => JSX.Element +>T : T +>props : T +>T : T +>JSX : any +>Element : JSX.Element + +const decorator = function (props: U) { +>decorator : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +} + +const decorator1 = function (props: U) { +>decorator1 : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>x : string +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +>x : string +} diff --git a/tests/baselines/reference/tsxGenericAttributesType8.js b/tests/baselines/reference/tsxGenericAttributesType8.js new file mode 100644 index 00000000000..435bf425c6a --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType8.js @@ -0,0 +1,22 @@ +//// [file.tsx] +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +var decorator = function (props) { + return ; +}; +var decorator1 = function (props) { + return ; +}; diff --git a/tests/baselines/reference/tsxGenericAttributesType8.symbols b/tests/baselines/reference/tsxGenericAttributesType8.symbols new file mode 100644 index 00000000000..516dbe9c322 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType8.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +declare function Component(props: T) : JSX.Element; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>props : Symbol(props, Decl(file.tsx, 2, 30)) +>T : Symbol(T, Decl(file.tsx, 2, 27)) +>JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) +>Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) + +const decorator = function (props: U) { +>decorator : Symbol(decorator, Decl(file.tsx, 3, 5)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +>U : Symbol(U, Decl(file.tsx, 3, 28)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 3, 31)) +} + +const decorator1 = function (props: U) { +>decorator1 : Symbol(decorator1, Decl(file.tsx, 7, 5)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) +>x : Symbol(x, Decl(file.tsx, 7, 40)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +>U : Symbol(U, Decl(file.tsx, 7, 29)) + + return ; +>Component : Symbol(Component, Decl(file.tsx, 0, 32)) +>props : Symbol(props, Decl(file.tsx, 7, 52)) +} diff --git a/tests/baselines/reference/tsxGenericAttributesType8.types b/tests/baselines/reference/tsxGenericAttributesType8.types new file mode 100644 index 00000000000..b2a62a575ff --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType8.types @@ -0,0 +1,38 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +declare function Component(props: T) : JSX.Element; +>Component : (props: T) => JSX.Element +>T : T +>props : T +>T : T +>JSX : any +>Element : JSX.Element + +const decorator = function (props: U) { +>decorator : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +} + +const decorator1 = function (props: U) { +>decorator1 : (props: U) => JSX.Element +>function (props: U) { return ;} : (props: U) => JSX.Element +>U : U +>x : string +>props : U +>U : U + + return ; +> : JSX.Element +>Component : (props: T) => JSX.Element +>props : U +} diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents3.types b/tests/baselines/reference/tsxStatelessFunctionComponents3.types index 714781058eb..879f8c75cdf 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents3.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponents3.types @@ -21,8 +21,8 @@ var MainMenu: React.StatelessComponent<{}> = (props) => (
>MainMenu : React.StatelessComponent<{}> >React : any >StatelessComponent : React.StatelessComponent

->(props) => (

Main Menu

) : (props: {}) => JSX.Element ->props : {} +>(props) => (

Main Menu

) : (props: { children?: React.ReactNode; }) => JSX.Element +>props : { children?: React.ReactNode; } >(

Main Menu

) : JSX.Element >

Main Menu

: JSX.Element >div : any @@ -40,7 +40,7 @@ var App: React.StatelessComponent<{ children }> = ({children}) => ( >React : any >StatelessComponent : React.StatelessComponent

>children : any ->({children}) => (

) : ({children}: { children: any; }) => JSX.Element +>({children}) => (
) : ({children}: { children: any; } & { children?: React.ReactNode; }) => JSX.Element >children : any >(
) : JSX.Element diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType5.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType5.tsx new file mode 100644 index 00000000000..d0215da7397 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType5.tsx @@ -0,0 +1,19 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + // Should be an ok but as of 2.3.3 this will be an error as we will instantiate B1.props to be empty object + return ; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType6.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType6.tsx new file mode 100644 index 00000000000..d70df8a0cf7 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType6.tsx @@ -0,0 +1,18 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +class B1 extends React.Component { + render() { + return
hi
; + } +} +class B extends React.Component { + props: U; + render() { + return ; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType7.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType7.tsx new file mode 100644 index 00000000000..3044fda23df --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType7.tsx @@ -0,0 +1,15 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType8.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType8.tsx new file mode 100644 index 00000000000..b1d3a7445c8 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType8.tsx @@ -0,0 +1,15 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +declare function Component(props: T) : JSX.Element; +const decorator = function (props: U) { + return ; +} + +const decorator1 = function (props: U) { + return ; +} \ No newline at end of file From f45f7579fc33617b9595a441823dce22e2c0c32a Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Thu, 11 May 2017 23:51:20 -0700 Subject: [PATCH 179/282] Adds CommaList to avoid large deeply nested comma expressions --- src/compiler/emitter.ts | 8 ++++++++ src/compiler/factory.ts | 16 +++++++++++++++- src/compiler/parser.ts | 2 ++ src/compiler/types.ts | 6 ++++++ src/compiler/utilities.ts | 4 ++++ src/compiler/visitor.ts | 8 ++++++++ 6 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 669c9f5dd36..c0d8cae861f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -733,6 +733,9 @@ namespace ts { // Transformation nodes case SyntaxKind.PartiallyEmittedExpression: return emitPartiallyEmittedExpression(node); + + case SyntaxKind.CommaList: + return emitCommaList(node); } } @@ -2101,6 +2104,10 @@ namespace ts { emitExpression(node.expression); } + function emitCommaList(node: CommaList) { + emitExpressionList(node, node.elements, ListFormat.CommaListElements); + } + /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -2951,6 +2958,7 @@ namespace ts { ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings, ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces, ArrayLiteralExpressionElements = PreserveLines | CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | Indented | SquareBrackets, + CommaListElements = CommaDelimited | SpaceBetweenSiblings | SingleLine, CallExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis, NewExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis | OptionalIfUndefined, TemplateExpressionSpans = SingleLine | NoInterveningComments, diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 2b781b6dbb3..7f84ffd534f 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2077,6 +2077,18 @@ namespace ts { return node; } + export function createCommaList(elements: Expression[]) { + const node = createSynthesizedNode(SyntaxKind.CommaList); + node.elements = createNodeArray(elements); + return node; + } + + export function updateCommaList(node: CommaList, elements: Expression[]) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + export function createBundle(sourceFiles: SourceFile[]) { const node = createNode(SyntaxKind.Bundle); node.sourceFiles = sourceFiles; @@ -2865,7 +2877,9 @@ namespace ts { } export function inlineExpressions(expressions: Expression[]) { - return reduceLeft(expressions, createComma); + return expressions.length > 10 + ? createCommaList(expressions) + : reduceLeft(expressions, createComma); } export function createExpressionFromEntityName(node: EntityName | Expression): Expression { diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index cc3fb24bdb8..1e8f7a1c904 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -362,6 +362,8 @@ namespace ts { return visitNode(cbNode, (node).expression); case SyntaxKind.MissingDeclaration: return visitNodes(cbNodes, node.decorators); + case SyntaxKind.CommaList: + return visitNodes(cbNodes, (node).elements); case SyntaxKind.JsxElement: return visitNode(cbNode, (node).openingElement) || diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a36378ade1d..5ad89bc469e 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -391,6 +391,7 @@ namespace ts { PartiallyEmittedExpression, MergeDeclarationMarker, EndOfDeclarationMarker, + CommaList, // Enum value count Count, @@ -1603,6 +1604,11 @@ namespace ts { kind: SyntaxKind.EndOfDeclarationMarker; } + export interface CommaList extends Expression { + kind: SyntaxKind.CommaList; + elements: NodeArray; + } + /** * Marks the beginning of a merged transformed declaration. */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 95b76286c59..ae54f9d3e76 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2327,6 +2327,9 @@ namespace ts { case SyntaxKind.SpreadElement: return 1; + case SyntaxKind.CommaList: + return 0; + default: return -1; } @@ -3915,6 +3918,7 @@ namespace ts { || kind === SyntaxKind.SpreadElement || kind === SyntaxKind.AsExpression || kind === SyntaxKind.OmittedExpression + || kind === SyntaxKind.CommaList || isUnaryExpressionKind(kind); } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index e434dadeaf7..7788c313139 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -876,6 +876,10 @@ namespace ts { return updatePartiallyEmittedExpression(node, visitNode((node).expression, visitor, isExpression)); + case SyntaxKind.CommaList: + return updateCommaList(node, + nodesVisitor((node).elements, visitor, isExpression)); + default: // No need to visit nodes with no children. return node; @@ -1389,6 +1393,10 @@ namespace ts { result = reduceNode((node).expression, cbNode, result); break; + case SyntaxKind.CommaList: + result = reduceNodes((node).elements, cbNodes, result); + break; + default: break; } From 22cf036ed91e638220520bb5ff5b167ee723180c Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 12 May 2017 09:57:39 -0700 Subject: [PATCH 180/282] Clean up naming, add documentation, flatten (some) nested commas --- src/compiler/core.ts | 29 +++++++++++++++++++++++++++++ src/compiler/emitter.ts | 6 +++--- src/compiler/factory.ts | 22 ++++++++++++++++++---- src/compiler/parser.ts | 4 ++-- src/compiler/types.ts | 9 ++++++--- src/compiler/utilities.ts | 4 ++-- src/compiler/visitor.ts | 10 +++++----- 7 files changed, 65 insertions(+), 19 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 321cc06f765..5e4afce98c8 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -490,6 +490,35 @@ namespace ts { return result; } + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | T[]): T[] { + let result: T[]; + if (array) { + for (let i = 0; i < array.length; i++) { + const item = array[i]; + const mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index c0d8cae861f..76423e45bd9 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -734,8 +734,8 @@ namespace ts { case SyntaxKind.PartiallyEmittedExpression: return emitPartiallyEmittedExpression(node); - case SyntaxKind.CommaList: - return emitCommaList(node); + case SyntaxKind.CommaListExpression: + return emitCommaList(node); } } @@ -2104,7 +2104,7 @@ namespace ts { emitExpression(node.expression); } - function emitCommaList(node: CommaList) { + function emitCommaList(node: CommaListExpression) { emitExpressionList(node, node.elements, ListFormat.CommaListElements); } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 7f84ffd534f..42f6a1267bc 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2077,13 +2077,25 @@ namespace ts { return node; } - export function createCommaList(elements: Expression[]) { - const node = createSynthesizedNode(SyntaxKind.CommaList); - node.elements = createNodeArray(elements); + function flattenCommaElements(node: Expression): Expression | Expression[] { + if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === SyntaxKind.CommaListExpression) { + return (node).elements; + } + if (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.CommaToken) { + return [node.left, node.right]; + } + } return node; } - export function updateCommaList(node: CommaList, elements: Expression[]) { + export function createCommaList(elements: Expression[]) { + const node = createSynthesizedNode(SyntaxKind.CommaListExpression); + node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements)); + return node; + } + + export function updateCommaList(node: CommaListExpression, elements: Expression[]) { return node.elements !== elements ? updateNode(createCommaList(elements), node) : node; @@ -2877,6 +2889,8 @@ namespace ts { } export function inlineExpressions(expressions: Expression[]) { + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. return expressions.length > 10 ? createCommaList(expressions) : reduceLeft(expressions, createComma); diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 1e8f7a1c904..dd189784a17 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -362,8 +362,8 @@ namespace ts { return visitNode(cbNode, (node).expression); case SyntaxKind.MissingDeclaration: return visitNodes(cbNodes, node.decorators); - case SyntaxKind.CommaList: - return visitNodes(cbNodes, (node).elements); + case SyntaxKind.CommaListExpression: + return visitNodes(cbNodes, (node).elements); case SyntaxKind.JsxElement: return visitNode(cbNode, (node).openingElement) || diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 5ad89bc469e..f38ec9abd9c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -389,9 +389,9 @@ namespace ts { // Transformation nodes NotEmittedStatement, PartiallyEmittedExpression, + CommaListExpression, MergeDeclarationMarker, EndOfDeclarationMarker, - CommaList, // Enum value count Count, @@ -1604,8 +1604,11 @@ namespace ts { kind: SyntaxKind.EndOfDeclarationMarker; } - export interface CommaList extends Expression { - kind: SyntaxKind.CommaList; + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + export interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; elements: NodeArray; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index ae54f9d3e76..1a981a0844f 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2327,7 +2327,7 @@ namespace ts { case SyntaxKind.SpreadElement: return 1; - case SyntaxKind.CommaList: + case SyntaxKind.CommaListExpression: return 0; default: @@ -3918,7 +3918,7 @@ namespace ts { || kind === SyntaxKind.SpreadElement || kind === SyntaxKind.AsExpression || kind === SyntaxKind.OmittedExpression - || kind === SyntaxKind.CommaList + || kind === SyntaxKind.CommaListExpression || isUnaryExpressionKind(kind); } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 7788c313139..517854e21ce 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -876,9 +876,9 @@ namespace ts { return updatePartiallyEmittedExpression(node, visitNode((node).expression, visitor, isExpression)); - case SyntaxKind.CommaList: - return updateCommaList(node, - nodesVisitor((node).elements, visitor, isExpression)); + case SyntaxKind.CommaListExpression: + return updateCommaList(node, + nodesVisitor((node).elements, visitor, isExpression)); default: // No need to visit nodes with no children. @@ -1393,8 +1393,8 @@ namespace ts { result = reduceNode((node).expression, cbNode, result); break; - case SyntaxKind.CommaList: - result = reduceNodes((node).elements, cbNodes, result); + case SyntaxKind.CommaListExpression: + result = reduceNodes((node).elements, cbNodes, result); break; default: From aaf6b83cb573c33c838f85a05d5029135a620b7c Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 12 May 2017 07:32:00 -0700 Subject: [PATCH 181/282] Don't goto aliased symbol with no declarations; and update tests --- src/services/goToDefinition.ts | 5 ++++- tests/cases/fourslash/ambientShorthandGotoDefinition.ts | 4 ++-- tests/cases/fourslash/goToDefinition_untypedModule.ts | 6 +++--- tests/cases/fourslash/quickInfoMeaning.ts | 8 ++++---- .../fourslash/tsxGoToDefinitionClassInDifferentFile.ts | 4 ++-- tests/cases/fourslash/untypedModuleImport.ts | 2 +- 6 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 946924bcf87..d0901de9a47 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -51,7 +51,10 @@ namespace ts.GoToDefinition { // import {A, B} from "mod"; // to jump to the implementation directly. if (symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) { - symbol = typeChecker.getAliasedSymbol(symbol); + const aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; + } } // Because name in short-hand property assignment has two different meanings: property name and property value, diff --git a/tests/cases/fourslash/ambientShorthandGotoDefinition.ts b/tests/cases/fourslash/ambientShorthandGotoDefinition.ts index 410fc932cec..74e348beb74 100644 --- a/tests/cases/fourslash/ambientShorthandGotoDefinition.ts +++ b/tests/cases/fourslash/ambientShorthandGotoDefinition.ts @@ -12,7 +12,7 @@ verify.quickInfoAt("useFoo", "import foo"); verify.goToDefinition({ - useFoo: "importFoo", + useFoo: "module", importFoo: "module" }); @@ -27,6 +27,6 @@ verify.goToDefinition({ verify.quickInfoAt("useBang", "import bang = require(\"jquery\")"); verify.goToDefinition({ - useBang: "importBang", + useBang: "module", importBang: "module" }); diff --git a/tests/cases/fourslash/goToDefinition_untypedModule.ts b/tests/cases/fourslash/goToDefinition_untypedModule.ts index b4571438434..fe29f7104cf 100644 --- a/tests/cases/fourslash/goToDefinition_untypedModule.ts +++ b/tests/cases/fourslash/goToDefinition_untypedModule.ts @@ -4,7 +4,7 @@ ////not read // @Filename: /a.ts -////import { f } from "foo"; -/////**/f(); +////import { /*def*/f } from "foo"; +/////*use*/f(); -verify.goToDefinition("", []); +verify.goToDefinition("use", "def"); diff --git a/tests/cases/fourslash/quickInfoMeaning.ts b/tests/cases/fourslash/quickInfoMeaning.ts index a3b9f988e1d..2c7aa5a0ccd 100644 --- a/tests/cases/fourslash/quickInfoMeaning.ts +++ b/tests/cases/fourslash/quickInfoMeaning.ts @@ -8,13 +8,13 @@ // @Filename: foo.d.ts ////declare const /*foo_value_declaration*/foo: number; ////declare module "foo_module" { -//// interface I { x: number; y: number } +//// interface /*foo_type_declaration*/I { x: number; y: number } //// export = I; ////} // @Filename: foo_user.ts /////// -////import /*foo_type_declaration*/foo = require("foo_module"); +////import foo = require("foo_module"); ////const x = foo/*foo_value*/; ////const i: foo/*foo_type*/ = { x: 1, y: 2 }; @@ -39,13 +39,13 @@ verify.goToDefinitionIs("foo_type_declaration"); // @Filename: bar.d.ts ////declare interface /*bar_type_declaration*/bar { x: number; y: number } ////declare module "bar_module" { -//// const x: number; +//// const /*bar_value_declaration*/x: number; //// export = x; ////} // @Filename: bar_user.ts /////// -////import /*bar_value_declaration*/bar = require("bar_module"); +////import bar = require("bar_module"); ////const x = bar/*bar_value*/; ////const i: bar/*bar_type*/ = { x: 1, y: 2 }; diff --git a/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts b/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts index f217e4096fc..7aa1c11fdc3 100644 --- a/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts +++ b/tests/cases/fourslash/tsxGoToDefinitionClassInDifferentFile.ts @@ -3,10 +3,10 @@ // @jsx: preserve // @Filename: C.tsx -////export default class C {} +////export default class /*def*/C {} // @Filename: a.tsx -////import /*def*/C from "./C"; +////import C from "./C"; ////const foo = ; verify.noErrors(); diff --git a/tests/cases/fourslash/untypedModuleImport.ts b/tests/cases/fourslash/untypedModuleImport.ts index 4dac6ac76bb..5501cec4792 100644 --- a/tests/cases/fourslash/untypedModuleImport.ts +++ b/tests/cases/fourslash/untypedModuleImport.ts @@ -17,6 +17,6 @@ const [r0, r1, r2] = test.ranges(); verify.singleReferenceGroup('"foo"', [r1]); goTo.marker("foo"); -verify.goToDefinitionIs([]); +verify.goToDefinitionIs("foo"); verify.quickInfoIs("import foo"); verify.singleReferenceGroup("import foo", [r0, r2]); From 8907c70a86843a3bc0f17c0cd815da017cafb950 Mon Sep 17 00:00:00 2001 From: Yui T Date: Fri, 12 May 2017 11:54:23 -0700 Subject: [PATCH 182/282] Address PR --- src/compiler/checker.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 03302ec5f32..14e789f17ae 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13549,17 +13549,17 @@ namespace ts { } function getApparentTypeOfJsxPropsType(propsType: Type): Type { - if (propsType) { - if (propsType.flags & TypeFlags.Intersection) { - const propsApprentType: Type[] = []; - for (const t of (propsType).types) { - propsApprentType.push(getApparentType(t)); - } - return getIntersectionType(propsApprentType); - } - return getApparentType(propsType); + if (!propsType) { + return undefined; } - return propsType; + if (propsType.flags & TypeFlags.Intersection) { + const propsApparentType: Type[] = []; + for (const t of (propsType).types) { + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); } /** From 99ea9c730f415ed150693f42acbd5f769b3ee012 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 11 May 2017 13:59:06 -0700 Subject: [PATCH 183/282] Add the members of interfaces that need to be implemented to class element completion --- src/services/completions.ts | 45 +- .../completionEntryForClassMembers.ts | 45 +- .../completionEntryForClassMembers2.ts | 456 ++++++++++++++++++ 3 files changed, 533 insertions(+), 13 deletions(-) create mode 100644 tests/cases/fourslash/completionEntryForClassMembers2.ts diff --git a/src/services/completions.ts b/src/services/completions.ts index 6be420c0919..1d7d27f92f4 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -937,7 +937,8 @@ namespace ts.Completions { hasFilteredClassMemberKeywords = true; const baseTypeNode = getClassExtendsHeritageClauseElement(classLikeDeclaration); - if (baseTypeNode) { + const implementsTypeNodes = getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { const classElement = contextToken.parent; let classElementModifierFlags = isClassElement(classElement) && getModifierFlags(classElement); // If this is context token is not something we are editing now, consider if this would lead to be modifier @@ -954,13 +955,27 @@ namespace ts.Completions { // No member list for private methods if (!(classElementModifierFlags & ModifierFlags.Private)) { - const baseType = typeChecker.getTypeAtLocation(baseTypeNode); - const typeToGetPropertiesFrom = (classElementModifierFlags & ModifierFlags.Static) ? - typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, classLikeDeclaration) : - baseType; + let baseClassTypeToGetPropertiesFrom: Type; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & ModifierFlags.Static) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation( + baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + const implementedInterfaceTypePropertySymbols = (classElementModifierFlags & ModifierFlags.Static) ? + undefined : + flatMap(implementsTypeNodes, typeNode => typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode))); // List of property symbols of base type that are not private and already implemented - symbols = filterClassMembersList(typeChecker.getPropertiesOfType(typeToGetPropertiesFrom), classLikeDeclaration.members, classElementModifierFlags); + symbols = filterClassMembersList( + baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, + implementedInterfaceTypePropertySymbols, + classLikeDeclaration.members, + classElementModifierFlags); } } } @@ -1334,7 +1349,7 @@ namespace ts.Completions { * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList(baseSymbols: Symbol[], existingMembers: ClassElement[], currentClassElementModifierFlags: ModifierFlags): Symbol[] { + function filterClassMembersList(baseSymbols: Symbol[], implementingTypeSymbols: Symbol[], existingMembers: ClassElement[], currentClassElementModifierFlags: ModifierFlags): Symbol[] { const existingMemberNames = createMap(); for (const m of existingMembers) { // Ignore omitted expressions for missing members @@ -1358,7 +1373,7 @@ namespace ts.Completions { // do not filter it out if the static presence doesnt match const mIsStatic = hasModifier(m, ModifierFlags.Static); const currentElementIsStatic = !!(currentClassElementModifierFlags & ModifierFlags.Static); - if ((mIsStatic && currentElementIsStatic) || + if ((mIsStatic && !currentElementIsStatic) || (!mIsStatic && currentElementIsStatic)) { continue; } @@ -1369,10 +1384,16 @@ namespace ts.Completions { } } - return filter(baseSymbols, baseProperty => - !existingMemberNames.get(baseProperty.name) && - baseProperty.getDeclarations() && - !(getDeclarationModifierFlagsFromSymbol(baseProperty) & ModifierFlags.Private)); + return concatenate( + filter(baseSymbols, baseProperty => isValidProperty(baseProperty, ModifierFlags.Private)), + filter(implementingTypeSymbols, implementingProperty => isValidProperty(implementingProperty, ModifierFlags.NonPublicAccessibilityModifier)) + ); + + function isValidProperty(propertySymbol: Symbol, inValidModifierFlags: ModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } } /** diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts index b242ca7ed78..527611b85bf 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -30,6 +30,18 @@ //// } //// /*classThatHasDifferentMethodThanBaseAfterProtectedMethod*/ ////} +////class D3 extends D1 { +//// /*classThatExtendsClassExtendingAnotherClass*/ +////} +////class D4 extends D1 { +//// static /*classThatExtendsClassExtendingAnotherClassAndTypesStatic*/ +////} +////class D5 extends D2 { +//// /*classThatExtendsClassExtendingAnotherClassWithOverridingMember*/ +////} +////class D6 extends D2 { +//// static /*classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic*/ +////} ////class E { //// /*classThatDoesNotExtendAnotherClass*/ ////} @@ -127,6 +139,12 @@ const allMembersOfBase: CompletionInfo[] = [ ["privateMethod", "(method) B.privateMethod(): void"], ["staticMethod", "(method) B.staticMethod(): void"] ]; +const publicCompletionInfoOfD1: CompletionInfo[] = [ + ["getValue1", "(method) D1.getValue1(): number"] +]; +const publicCompletionInfoOfD2: CompletionInfo[] = [ + ["protectedMethod", "(method) D2.protectedMethod(): void"] +]; function filterCompletionInfo(fn: (a: CompletionInfo) => boolean): CompletionInfoVerifier { const validMembers: CompletionInfo[] = []; const invalidMembers: CompletionInfo[] = []; @@ -147,6 +165,19 @@ const staticMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "st const instanceWithoutProtectedMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue"); const instanceWithoutPublicMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "protectedMethod"); +const instanceMemberInfoD1: CompletionInfoVerifier = { + validMembers: instanceMemberInfo.validMembers.concat(publicCompletionInfoOfD1), + invalidMembers: instanceMemberInfo.invalidMembers +}; +const instanceMemberInfoD2: CompletionInfoVerifier = { + validMembers: instanceWithoutProtectedMemberInfo.validMembers.concat(publicCompletionInfoOfD2), + invalidMembers: instanceWithoutProtectedMemberInfo.invalidMembers +}; +const staticMemberInfoDn: CompletionInfoVerifier = { + validMembers: staticMemberInfo.validMembers, + invalidMembers: staticMemberInfo.invalidMembers.concat(publicCompletionInfoOfD1, publicCompletionInfoOfD2) +}; + // Not a class element declaration location const nonClassElementMarkers = [ "InsideMethod" @@ -210,4 +241,16 @@ const classInstanceElementWithoutProtectedMethodLocations = [ "classThatHasAlreadyImplementedAnotherClassProtectedMethod", "classThatHasDifferentMethodThanBaseAfterProtectedMethod", ]; -verifyClassElementLocations(instanceWithoutProtectedMemberInfo, classInstanceElementWithoutProtectedMethodLocations); \ No newline at end of file +verifyClassElementLocations(instanceWithoutProtectedMemberInfo, classInstanceElementWithoutProtectedMethodLocations); + +// instance memebers in D1 and base class are shown +verifyClassElementLocations(instanceMemberInfoD1, ["classThatExtendsClassExtendingAnotherClass"]); + +// instance memebers in D2 and base class are shown +verifyClassElementLocations(instanceMemberInfoD2, ["classThatExtendsClassExtendingAnotherClassWithOverridingMember"]); + +// static base members and class member keywords allowed +verifyClassElementLocations(staticMemberInfoDn, [ + "classThatExtendsClassExtendingAnotherClassAndTypesStatic", + "classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic" +]); \ No newline at end of file diff --git a/tests/cases/fourslash/completionEntryForClassMembers2.ts b/tests/cases/fourslash/completionEntryForClassMembers2.ts new file mode 100644 index 00000000000..539702196a3 --- /dev/null +++ b/tests/cases/fourslash/completionEntryForClassMembers2.ts @@ -0,0 +1,456 @@ +/// + +////interface I { +//// methodOfInterface(): number; +////} +////interface I2 { +//// methodOfInterface2(): number; +////} +////interface I3 { +//// getValue(): string; +//// method(): string; +////} +////interface I4 { +//// staticMethod(): void; +//// method(): string; +////} +////class B0 { +//// private privateMethod() { } +//// protected protectedMethod() { } +//// static staticMethod() { } +//// getValue(): string | boolean { return "hello"; } +//// private privateMethod1() { } +//// protected protectedMethod1() { } +//// static staticMethod1() { } +//// getValue1(): string | boolean { return "hello"; } +////} +////interface I5 extends B0 { +//// methodOfInterface5(): number; +////} +////interface I6 extends B0 { +//// methodOfInterface6(): number; +//// staticMethod(): void; +////} +////interface I7 extends I { +//// methodOfInterface7(): number; +////} +////class B { +//// private privateMethod() { } +//// protected protectedMethod() { } +//// static staticMethod() { } +//// getValue(): string | boolean { return "hello"; } +////} +////class C0 implements I, I2 { +//// /*implementsIAndI2*/ +////} +////class C00 implements I, I2 { +//// static /*implementsIAndI2AndWritingStatic*/ +////} +////class C001 implements I, I2 { +//// methodOfInterface/*implementsIAndI2AndWritingMethodNameOfI*/ +////} +////class C extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2*/ +////} +////class C1 extends B implements I, I2 { +//// static /*extendsBAndImplementsIAndI2AndWritingStatic*/ +////} +////class D extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2WithMethodFromB*/ +//// protected protectedMethod() { +//// return "protected"; +//// } +////} +////class E extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2WithMethodFromI*/ +//// methodOfInterface() { +//// return 1; +//// } +////} +////class F extends B implements I, I2 { +//// /*extendsBAndImplementsIAndI2WithMethodFromBAndI*/ +//// protected protectedMethod() { +//// return "protected" +//// } +//// methodOfInterface() { +//// return 1; +//// } +////} +////class F2 extends B implements I, I2 { +//// protected protectedMethod() { +//// return "protected" +//// } +//// methodOfInterface() { +//// return 1; +//// } +//// static /*extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic*/ +////} +////class G extends B implements I3 { +//// /*extendsBAndImplementsI3WithSameNameMembers*/ +////} +////class H extends B implements I3 { +//// /*extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember*/ +//// getValue() { +//// return "hello"; +//// } +////} +////class J extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethod*/ +////} +////class L extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod*/ +//// staticMethod2() { +//// return "hello"; +//// } +////} +////class K extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod*/ +//// staticMethod() { +//// return "hello"; +//// } +////} +////class M extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic*/ +//// static staticMethod() { +//// return "hello"; +//// } +////} +////class N extends B0 implements I4 { +//// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth*/ +//// staticMethod() { +//// return "hello"; +//// } +//// static staticMethod() { +//// return "hello"; +//// } +////} +////class J1 extends B0 implements I4 { +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic*/ +////} +////class L1 extends B0 implements I4 { +//// staticMethod2() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic*/ +////} +////class K1 extends B0 implements I4 { +//// staticMethod() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic*/ +////} +////class M1 extends B0 implements I4 { +//// static staticMethod() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic*/ +////} +////class N1 extends B0 implements I4 { +//// staticMethod() { +//// return "hello"; +//// } +//// static staticMethod() { +//// return "hello"; +//// } +//// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic*/ +////} +////class O implements I7 { +//// /*implementsI7whichExtendsI*/ +////} +////class P implements I7, I { +//// /*implementsI7whichExtendsIAndAlsoImplementsI*/ +////} +////class Q implements I, I7 { +//// /*implementsIAndAlsoImplementsI7whichExtendsI*/ +////} +////class R implements I5 { +//// /*implementsI5ThatExtendsB0*/ +////} +////class S implements I6 { +//// /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ +////} +////class T extends B0 implements I5 { +//// /*extendsB0AndImplementsI5ThatExtendsB0*/ +////} +////class U extends B0 implements I6 { +//// /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ +////} +////class R1 implements I5 { +//// static /*implementsI5ThatExtendsB0TypesStatic*/ +////} +////class S1 implements I6 { +//// static /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ +////} +////class T1 extends B0 implements I5 { +//// static /*extendsB0AndImplementsI5ThatExtendsB0TypesStatic*/ +////} +////class U1 extends B0 implements I6 { +//// static /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ +////} + +const allowedKeywordCount = verify.allowedClassElementKeywords.length; +type CompletionInfo = [string, string]; +type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] }; + +function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) { + for (const marker of classElementCompletionLocations) { + goTo.marker(marker); + verifyCompletionInfo(validMembers, verify); + verifyCompletionInfo(invalidMembers, verify.not); + verify.completionListContainsClassElementKeywords(); + verify.completionListCount(allowedKeywordCount + validMembers.length); + } +} + +function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) { + for (const [symbol, text] of memberInfo) { + verify.completionListContains(symbol, text, /*documentation*/ undefined, "method"); + } +} + +const validInstanceMembersOfBaseClassB: CompletionInfo[] = [ + ["getValue", "(method) B.getValue(): string | boolean"], + ["protectedMethod", "(method) B.protectedMethod(): void"], +]; +const validStaticMembersOfBaseClassB: CompletionInfo[] = [ + ["staticMethod", "(method) B.staticMethod(): void"] +]; +const privateMembersOfBaseClassB: CompletionInfo[] = [ + ["privateMethod", "(method) B.privateMethod(): void"], +]; +const protectedPropertiesOfBaseClassB0: CompletionInfo[] = [ + ["protectedMethod", "(method) B0.protectedMethod(): void"], + ["protectedMethod1", "(method) B0.protectedMethod1(): void"], +]; +const publicPropertiesOfBaseClassB0: CompletionInfo[] = [ + ["getValue", "(method) B0.getValue(): string | boolean"], + ["getValue1", "(method) B0.getValue1(): string | boolean"], +]; +const validInstanceMembersOfBaseClassB0: CompletionInfo[] = protectedPropertiesOfBaseClassB0.concat(publicPropertiesOfBaseClassB0); +const validStaticMembersOfBaseClassB0: CompletionInfo[] = [ + ["staticMethod", "(method) B0.staticMethod(): void"], + ["staticMethod1", "(method) B0.staticMethod1(): void"] +]; +const privateMembersOfBaseClassB0: CompletionInfo[] = [ + ["privateMethod", "(method) B0.privateMethod(): void"], + ["privateMethod1", "(method) B0.privateMethod1(): void"], +]; +const membersOfI: CompletionInfo[] = [ + ["methodOfInterface", "(method) I.methodOfInterface(): number"], +]; +const membersOfI2: CompletionInfo[] = [ + ["methodOfInterface2", "(method) I2.methodOfInterface2(): number"], +]; +const membersOfI3: CompletionInfo[] = [ + ["getValue", "(method) I3.getValue(): string"], + ["method", "(method) I3.method(): string"], +]; +const membersOfI4: CompletionInfo[] = [ + ["staticMethod", "(method) I4.staticMethod(): void"], + ["method", "(method) I4.method(): string"], +]; +const membersOfI5: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ + ["methodOfInterface5", "(method) I5.methodOfInterface5(): number"] +]); +const membersOfI6: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ + ["staticMethod", "(method) I6.staticMethod(): void"], + ["methodOfInterface6", "(method) I6.methodOfInterface6(): number"] +]); +const membersOfI7: CompletionInfo[] = membersOfI.concat([ + ["methodOfInterface7", "(method) I7.methodOfInterface7(): number"] +]); + +function getCompletionInfoVerifier( + validMembers: CompletionInfo[], + invalidMembers: CompletionInfo[], + arrayToDistribute: CompletionInfo[], + isValidDistributionCriteria: (v: CompletionInfo) => boolean): CompletionInfoVerifier { + if (arrayToDistribute) { + validMembers = validMembers.concat(arrayToDistribute.filter(isValidDistributionCriteria)); + invalidMembers = invalidMembers.concat(arrayToDistribute.filter(v => !isValidDistributionCriteria(v))); + } + return { + validMembers, + invalidMembers + } +} + +const noMembers: CompletionInfo[] = []; +const membersOfIAndI2 = membersOfI.concat(membersOfI2); +const invalidMembersOfBAtInstanceLocation = privateMembersOfBaseClassB.concat(validStaticMembersOfBaseClassB); + +// members of I and I2 +verifyClassElementLocations({ validMembers: membersOfIAndI2, invalidMembers: noMembers }, [ + "implementsIAndI2", + "implementsIAndI2AndWritingMethodNameOfI" +]); + +// Static location so no members of I and I2 +verifyClassElementLocations({ validMembers: noMembers, invalidMembers: membersOfIAndI2 }, + ["implementsIAndI2AndWritingStatic"]); + +const allInstanceBAndIAndI2 = membersOfIAndI2.concat(validInstanceMembersOfBaseClassB); +// members of instance B, I and I2 +verifyClassElementLocations({ + validMembers: allInstanceBAndIAndI2, + invalidMembers: invalidMembersOfBAtInstanceLocation +}, ["extendsBAndImplementsIAndI2"]); + +// static location so only static members of B and no members of instance B, I and I2 +verifyClassElementLocations({ + validMembers: validStaticMembersOfBaseClassB, + invalidMembers: privateMembersOfBaseClassB.concat(allInstanceBAndIAndI2) +}, [ + "extendsBAndImplementsIAndI2AndWritingStatic", + "extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic" + ]); + +// instance members of B without protectedMethod, I and I2 +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ membersOfIAndI2, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ validInstanceMembersOfBaseClassB, + value => value[0] !== "protectedMethod"), + ["extendsBAndImplementsIAndI2WithMethodFromB"]); + +// instance members of B, members of T without methodOfInterface and I2 +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ membersOfI2.concat(validInstanceMembersOfBaseClassB), + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI, + value => value[0] !== "methodOfInterface"), + ["extendsBAndImplementsIAndI2WithMethodFromI"]); + +// instance members of B without protectedMethod, members of T without methodOfInterface and I2 +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ membersOfI2, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI.concat(validInstanceMembersOfBaseClassB), + value => value[0] !== "methodOfInterface" && value[0] !== "protectedMethod"), + ["extendsBAndImplementsIAndI2WithMethodFromBAndI"]); + +// members of B and members of I3 that are not same as name of method in B +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ validInstanceMembersOfBaseClassB, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI3, + value => value[0] !== "getValue"), + ["extendsBAndImplementsI3WithSameNameMembers"]); + +// members of B (without getValue since its implemented) and members of I3 that are not same as name of method in B +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ noMembers, + /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, + /*arrayToDistribute*/ membersOfI3.concat(validInstanceMembersOfBaseClassB), + value => value[0] !== "getValue"), + ["extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember"]); + +const invalidMembersOfB0AtInstanceSide = privateMembersOfBaseClassB0.concat(validStaticMembersOfBaseClassB0); +const invalidMembersOfB0AtStaticSide = privateMembersOfBaseClassB0.concat(validInstanceMembersOfBaseClassB0); +// members of B0 and members of I4 +verifyClassElementLocations({ + validMembers: validInstanceMembersOfBaseClassB0.concat(membersOfI4), + invalidMembers: invalidMembersOfB0AtInstanceSide +}, [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic" + ]); + +// members of B0 and members of I4 that are not staticMethod +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ validInstanceMembersOfBaseClassB0, + /*invalidMembers*/ invalidMembersOfB0AtInstanceSide, + /*arrayToDistribute*/ membersOfI4, + value => value[0] !== "staticMethod" + ), [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth" + ]); + +// static members of B0 +verifyClassElementLocations({ + validMembers: validStaticMembersOfBaseClassB0, + invalidMembers: invalidMembersOfB0AtStaticSide.concat(membersOfI4) +}, [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic" + ]); + +// static members of B0 without staticMethod +verifyClassElementLocations( + getCompletionInfoVerifier( + /*validMembers*/ noMembers, + /*invalidMembers*/ invalidMembersOfB0AtStaticSide.concat(membersOfI4), + /*arrayToDistribute*/ validStaticMembersOfBaseClassB0, + value => value[0] !== "staticMethod" + ), [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic" + ]); + +// members of I7 extends I +verifyClassElementLocations({ validMembers: membersOfI7, invalidMembers: noMembers }, [ + "implementsI7whichExtendsI", + "implementsI7whichExtendsIAndAlsoImplementsI", + "implementsIAndAlsoImplementsI7whichExtendsI" +]); + +const invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 = invalidMembersOfB0AtInstanceSide + .concat(protectedPropertiesOfBaseClassB0); +// members of I5 extends B0 +verifyClassElementLocations({ + validMembers: membersOfI5, + invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 +}, [ + "implementsI5ThatExtendsB0", + ]); + +// members of I6 extends B0 +verifyClassElementLocations({ + validMembers: membersOfI6, + invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 +}, [ + "implementsI6ThatExtendsB0AndHasStaticMethodOfB0", + ]); + +// members of B0 and I5 that extends B0 +verifyClassElementLocations({ + validMembers: membersOfI5.concat(protectedPropertiesOfBaseClassB0), + invalidMembers: invalidMembersOfB0AtInstanceSide +}, [ + "extendsB0AndImplementsI5ThatExtendsB0" + ]); + +// members of B0 and I6 that extends B0 +verifyClassElementLocations({ + validMembers: membersOfI6.concat(protectedPropertiesOfBaseClassB0), + invalidMembers: invalidMembersOfB0AtInstanceSide +}, [ + "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0" + ]); + +// nothing on static side as these do not extend any other class +verifyClassElementLocations({ + validMembers: [], + invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) +}, [ + "implementsI5ThatExtendsB0TypesStatic", + "implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" + ]); + +// statics of base B but nothing from instance side +verifyClassElementLocations({ + validMembers: validStaticMembersOfBaseClassB0, + invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) +}, [ + "extendsB0AndImplementsI5ThatExtendsB0TypesStatic", + "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" + ]); \ No newline at end of file From 0588f8b3800097513c3029c8b8f20ffba443c5c1 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 12 May 2017 13:25:15 -0700 Subject: [PATCH 184/282] cleanup --- src/compiler/checker.ts | 46 +++++++++++++---------------------------- src/compiler/factory.ts | 9 -------- 2 files changed, 14 insertions(+), 41 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3ce73b3283e..3d040bd284e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2436,24 +2436,17 @@ namespace ts { Debug.assert(!!(type.flags & TypeFlags.Object)); return typeReferenceToTypeNode(type); } - if (objectFlags & ObjectFlags.ClassOrInterface) { - Debug.assert(!!(type.flags & TypeFlags.Object)); - const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); - return createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & TypeFlags.TypeParameter) { + if (type.flags & TypeFlags.TypeParameter || objectFlags & ObjectFlags.ClassOrInterface) { const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!inTypeAlias && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { const name = symbolToTypeReferenceName(type.aliasSymbol); const typeArgumentNodes = toTypeArgumentNodes(type.aliasTypeArguments, context); return createTypeReferenceNode(name, typeArgumentNodes); } - if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; const typeNodes = types && mapToTypeNodeArray(types, context, /*addInElementTypeFlag*/ true, /*addInFirstTypeArgumentFlag*/ false); @@ -2468,13 +2461,11 @@ namespace ts { return undefined; } } - if (objectFlags & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) { Debug.assert(!!(type.flags & TypeFlags.Object)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & TypeFlags.Index) { const indexedType = (type).type; context.flags |= NodeBuilderFlags.InElementType; @@ -2482,7 +2473,6 @@ namespace ts { Debug.assert(!(context.flags & NodeBuilderFlags.InElementType)); return createTypeOperatorNode(indexTypeNode); } - if (type.flags & TypeFlags.IndexedAccess) { context.flags |= NodeBuilderFlags.InElementType; const objectTypeNode = typeToTypeNodeHelper((type).objectType, context); @@ -2495,13 +2485,10 @@ namespace ts { function createMappedTypeNodeFromType(type: MappedType) { Debug.assert(!!(type.flags & TypeFlags.Object)); - const typeParameter = getTypeParameterFromMappedType(type); - const typeParameterNode = typeParameterToDeclaration(typeParameter, context); - - const templateType = getTemplateTypeFromMappedType(type); - const templateTypeNode = typeToTypeNodeHelper(templateType, context); const readonlyToken = type.declaration && type.declaration.readonlyToken ? createToken(SyntaxKind.ReadonlyKeyword) : undefined; const questionToken = type.declaration && type.declaration.questionToken ? createToken(SyntaxKind.QuestionToken) : undefined; + const typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + const templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); const mappedTypeNode = createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return setEmitFlags(mappedTypeNode, EmitFlags.SingleLine); @@ -2521,7 +2508,7 @@ namespace ts { const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - const entityName = symbolToName(typeAlias, context, SymbolFlags.Type, /*expectsIdentifier*/ false ); + const entityName = symbolToName(typeAlias, context, SymbolFlags.Type, /*expectsIdentifier*/ false); return createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -2802,8 +2789,8 @@ namespace ts { } function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { - const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword); const name = getNameFromIndexInfo(indexInfo) || "x"; + const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword); const indexingParameter = createParameter( /*decorators*/ undefined, @@ -2851,37 +2838,32 @@ namespace ts { } function typeParameterToDeclaration(type: TypeParameter, context: NodeBuilderContext): TypeParameterDeclaration { + const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ true); const constraint = getConstraintFromTypeParameter(type); const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); const defaultParameter = getDefaultFromTypeParameter(type); const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ true); return createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol: Symbol, context: NodeBuilderContext): ParameterDeclaration { const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); + const modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(getSynthesizedClone); + const dotDotDotToken = isRestParameter(parameterDeclaration) ? createToken(SyntaxKind.DotDotDotToken) : undefined; + const name = parameterDeclaration.name.kind === SyntaxKind.Identifier ? + getSynthesizedClone(parameterDeclaration.name) : + cloneBindingName(parameterDeclaration.name); + const questionToken = isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : undefined; + let parameterType = getTypeOfSymbol(parameterSymbol); if (isRequiredInitializedParameter(parameterDeclaration)) { parameterType = includeFalsyTypes(parameterType, TypeFlags.Undefined); } const parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - let name: BindingName; - if (parameterDeclaration.name.kind === SyntaxKind.Identifier) { - name = getSynthesizedClone(parameterDeclaration.name); - } - else { - Debug.assert(parameterDeclaration.name.kind === SyntaxKind.ArrayBindingPattern || parameterDeclaration.name.kind === SyntaxKind.ObjectBindingPattern); - name = cloneBindingName(parameterDeclaration.name); - } - const questionToken = isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : undefined; - const dotDotDotToken = (parameterDeclaration ? isRestParameter(parameterDeclaration) : isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) ? - createToken(SyntaxKind.DotDotDotToken) : - undefined; const parameterNode = createParameter( /*decorators*/ undefined, - cloneNodeArray(parameterDeclaration.modifiers), + modifiers, dotDotDotToken, name, questionToken, diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 230eb678ee5..97ee45aedcc 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -84,15 +84,6 @@ namespace ts { return clone; } - export function getDeepSynthesizedClone(node: T | undefined): T { - const clone = visitEachChild(node, getDeepSynthesizedClone, nullTransformationContext, /*nodeVisitor*/ undefined, getSynthesizedClone); - return nodeIsSynthesized(clone) ? clone : getSynthesizedClone(clone); - } - - export function cloneNodeArray(nodeArray: NodeArray) { - return nodeArray && nodeArray.map(getDeepSynthesizedClone); - } - // Literals export function createLiteral(value: string): StringLiteral; From ca748d6c02fb7cbd208d6b2ad9aaa43e4b1b8c66 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Fri, 12 May 2017 14:48:13 -0700 Subject: [PATCH 185/282] Add insertSpaceAfterTypeAssertion to the server protocol --- src/server/protocol.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 428b69027c7..c4c9ecece2b 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2267,6 +2267,7 @@ namespace ts.server.protocol { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; From 4240f6f5d9fedf3134f82ca23e1e9f7d74cc7422 Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Fri, 12 May 2017 16:17:32 -0700 Subject: [PATCH 186/282] Extract diagnostics formatter used by --pretty This allows compilers other than tsc.js to display nice in-context diagnostics --- src/compiler/program.ts | 95 +++++++++++++++++++++++++++++++++++++++++ src/compiler/tsc.ts | 87 +------------------------------------ 2 files changed, 96 insertions(+), 86 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 7893fee651e..8233ab4802e 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -241,6 +241,101 @@ namespace ts { return output; } + const redForegroundEscapeSequence = "\u001b[91m"; + const yellowForegroundEscapeSequence = "\u001b[93m"; + const blueForegroundEscapeSequence = "\u001b[93m"; + const gutterStyleSequence = "\u001b[100;30m"; + const gutterSeparator = " "; + const resetEscapeSequence = "\u001b[0m"; + const ellipsis = "..."; + function getCategoryFormat(category: DiagnosticCategory): string { + switch (category) { + case DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case DiagnosticCategory.Error: return redForegroundEscapeSequence; + case DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + + function formatAndReset(text: string, formatStyle: string) { + return formatStyle + text + resetEscapeSequence; + } + + function padLeft(s: string, length: number) { + while (s.length < length) { + s = " " + s; + } + return s; + } + + export function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string { + let output = ""; + for (const diagnostic of diagnostics) { + if (diagnostic.file) { + const { start, length, file } = diagnostic; + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); + const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; + const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName; + + const hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + let gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + + output += sys.newLine; + for (let i = firstLine; i <= lastLine; i++) { + // 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) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine; + i = lastLine - 1; + } + + const lineStart = getPositionOfLineAndCharacter(file, i, 0); + const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + let lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + + // Output the gutter and the actual contents of the line. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + sys.newLine; + + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + const lastCharForLine = i === lastLine ? lastLineChar : undefined; + + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + + output += sys.newLine; + } + + output += sys.newLine; + output += `${ relativeFileName }(${ firstLine + 1 },${ firstLineChar + 1 }): `; + } + + const categoryColor = getCategoryFormat(diagnostic.category); + const category = DiagnosticCategory[diagnostic.category].toLowerCase(); + output += `${ formatAndReset(category, categoryColor) } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }`; + } + return output; + } + export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string { if (typeof messageText === "string") { return messageText; diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 8981da65ba3..834c7326e22 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -60,93 +60,8 @@ namespace ts { sys.write(ts.formatDiagnostics([diagnostic], host)); } - const redForegroundEscapeSequence = "\u001b[91m"; - const yellowForegroundEscapeSequence = "\u001b[93m"; - const blueForegroundEscapeSequence = "\u001b[93m"; - const gutterStyleSequence = "\u001b[100;30m"; - const gutterSeparator = " "; - const resetEscapeSequence = "\u001b[0m"; - const ellipsis = "..."; - function getCategoryFormat(category: DiagnosticCategory): string { - switch (category) { - case DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case DiagnosticCategory.Error: return redForegroundEscapeSequence; - case DiagnosticCategory.Message: return blueForegroundEscapeSequence; - } - } - - function formatAndReset(text: string, formatStyle: string) { - return formatStyle + text + resetEscapeSequence; - } - function reportDiagnosticWithColorAndContext(diagnostic: Diagnostic, host: FormatDiagnosticsHost): void { - let output = ""; - - if (diagnostic.file) { - const { start, length, file } = diagnostic; - const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); - const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); - const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; - const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName; - - const hasMoreThanFiveLines = (lastLine - firstLine) >= 4; - let gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - - output += sys.newLine; - for (let i = firstLine; i <= lastLine; i++) { - // 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) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine; - i = lastLine - 1; - } - - const lineStart = getPositionOfLineAndCharacter(file, i, 0); - const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - let lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces - - // Output the gutter and the actual contents of the line. - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + sys.newLine; - - // Output the gutter and the error span for the line using tildes. - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; - if (i === firstLine) { - // If we're on the last line, then limit it to the last character of the last line. - // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. - const lastCharForLine = i === lastLine ? lastLineChar : undefined; - - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - // Squiggle the entire line. - output += lineContent.replace(/./g, "~"); - } - output += resetEscapeSequence; - - output += sys.newLine; - } - - output += sys.newLine; - output += `${ relativeFileName }(${ firstLine + 1 },${ firstLineChar + 1 }): `; - } - - const categoryColor = getCategoryFormat(diagnostic.category); - const category = DiagnosticCategory[diagnostic.category].toLowerCase(); - output += `${ formatAndReset(category, categoryColor) } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }`; - output += sys.newLine + sys.newLine; - - sys.write(output); + sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + sys.newLine + sys.newLine); } function reportWatchDiagnostic(diagnostic: Diagnostic) { From a32bc985bfeca89c32f0d7c10e83563dc115ef6e Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 12 May 2017 16:27:35 -0700 Subject: [PATCH 187/282] respond to comments --- src/compiler/checker.ts | 65 +++++++++++++++++++-------------------- src/compiler/emitter.ts | 21 +++++++------ src/compiler/factory.ts | 60 +++++++++++++++++++----------------- src/compiler/types.ts | 28 ++++++++--------- src/compiler/utilities.ts | 2 -- src/compiler/visitor.ts | 12 ++++++++ src/services/services.ts | 2 +- 7 files changed, 101 insertions(+), 89 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3d040bd284e..a4c5f401321 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2278,35 +2278,10 @@ namespace ts { return result; } - function typeFormatFlagsToNodeBuilderFlags(flags: TypeFormatFlags): NodeBuilderFlags { - let result = NodeBuilderFlags.None; - if (flags === TypeFormatFlags.None) { - return result; - } - if (flags & TypeFormatFlags.NoTruncation) { - result |= NodeBuilderFlags.NoTruncation; - } - if (flags & TypeFormatFlags.UseFullyQualifiedType) { - result |= NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & TypeFormatFlags.SuppressAnyReturnType) { - result |= NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & TypeFormatFlags.WriteArrayAsGenericType) { - result |= NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & TypeFormatFlags.WriteTypeArgumentsOfSignature) { - result |= NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - - return result; - } - function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, typeFormatFlagsToNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors); + const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors); Debug.assert(typeNode !== undefined, "should always get typenode?"); - const newLine = NewLineKind.None; - const options = { newLine, removeComments: true }; + const options = { removeComments: true }; const writer = createTextWriter(""); const printer = createPrinter(options, writer); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); @@ -2318,6 +2293,30 @@ namespace ts { return result.substr(0, maxLength - "...".length) + "..."; } return result; + + function toNodeBuilderFlags(flags?: TypeFormatFlags): NodeBuilderFlags { + let result = NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & TypeFormatFlags.NoTruncation) { + result |= NodeBuilderFlags.NoTruncation; + } + if (flags & TypeFormatFlags.UseFullyQualifiedType) { + result |= NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & TypeFormatFlags.SuppressAnyReturnType) { + result |= NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & TypeFormatFlags.WriteArrayAsGenericType) { + result |= NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & TypeFormatFlags.WriteTypeArgumentsOfSignature) { + result |= NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + + return result; + } } function createNodeBuilder() { @@ -2423,7 +2422,7 @@ namespace ts { } if (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType) { if (context.flags & NodeBuilderFlags.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowThisInObjectLiteral)) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -2455,7 +2454,7 @@ namespace ts { return inElementType ? createParenthesizedType(unionOrIntersectionTypeNode) : unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; @@ -2629,7 +2628,7 @@ namespace ts { return createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -2901,7 +2900,7 @@ namespace ts { if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -2923,7 +2922,7 @@ namespace ts { } } if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowTypeParameterInQualifiedName)) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowTypeParameterInQualifiedName)) { context.encounteredError = true; } typeParameterNodes = toTypeArgumentNodes(typeParameters, context); @@ -2981,7 +2980,7 @@ namespace ts { if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { return declarationNameToString((declaration.parent).name); } - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowAnonymousIdentifier)) { + if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowAnonymousIdentifier)) { context.encounteredError = true; } switch (declaration.kind) { diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index d943e91b497..30e5ba1a091 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -234,12 +234,7 @@ namespace ts { writeBundle }; - /** - * If `sourceFile` is `undefined`, `node` must be a synthesized `TypeNode`. - */ - function printNode(hint: EmitHint, node: TypeNode, sourceFile: undefined): string; - function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; - function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined): string { + function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string { switch (hint) { case EmitHint.SourceFile: Debug.assert(isSourceFile(node), "Expected a SourceFile node."); @@ -269,6 +264,11 @@ namespace ts { return endPrint(); } + /** + * If `sourceFile` is `undefined`, `node` must be a synthesized `TypeNode`. + */ + function writeNode(hint: EmitHint, node: TypeNode, sourceFile: undefined, output: EmitTextWriter): void; + function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter): void; function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, output: EmitTextWriter) { const previousWriter = writer; setWriter(output); @@ -961,6 +961,7 @@ namespace ts { function emitTypeLiteral(node: TypeLiteralNode) { write("{"); + // TODO: fix added indentation so we can remove this check. if (node.members.length > 0) { emitList(node, node.members, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers); } @@ -2525,7 +2526,7 @@ namespace ts { const firstChild = children[0]; if (firstChild === undefined) { - return !(rangeIsOnSingleLine(parentNode, currentSourceFile)); + return !rangeIsOnSingleLine(parentNode, currentSourceFile); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(firstChild)) { return synthesizedNodeStartsOnNewLine(firstChild, format); @@ -2551,7 +2552,7 @@ namespace ts { return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); } else { - return !(rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile)); + return !rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); } } else { @@ -2570,13 +2571,13 @@ namespace ts { const lastChild = lastOrUndefined(children); if (lastChild === undefined) { - return !(rangeIsOnSingleLine(parentNode, currentSourceFile)); + return !rangeIsOnSingleLine(parentNode, currentSourceFile); } else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(lastChild)) { return synthesizedNodeStartsOnNewLine(lastChild, format); } else { - return !(rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile)); + return !rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); } } else { diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 97ee45aedcc..45aa14bdd2b 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2,26 +2,6 @@ /// namespace ts { - export const nullTransformationContext: TransformationContext = { - enableEmitNotification: noop, - enableSubstitution: noop, - endLexicalEnvironment: () => undefined, - getCompilerOptions: notImplemented, - getEmitHost: notImplemented, - getEmitResolver: notImplemented, - hoistFunctionDeclaration: noop, - hoistVariableDeclaration: noop, - isEmitNotificationEnabled: notImplemented, - isSubstitutionEnabled: notImplemented, - onEmitNode: noop, - onSubstituteNode: notImplemented, - readEmitHelpers: notImplemented, - requestEmitHelper: noop, - resumeLexicalEnvironment: noop, - startLexicalEnvironment: noop, - suspendLexicalEnvironment: noop - }; - function createSynthesizedNode(kind: SyntaxKind): Node { const node = createNode(kind, -1, -1); node.flags |= NodeFlags.Synthesized; @@ -127,13 +107,18 @@ namespace ts { // Identifiers + export function createIdentifier(text: string): Identifier; + /* @internal */ + export function createIdentifier(text: string, typeArguments: TypeNode[]): Identifier; export function createIdentifier(text: string, typeArguments?: TypeNode[]): Identifier { const node = createSynthesizedNode(SyntaxKind.Identifier); node.text = escapeIdentifier(text); node.originalKeywordKind = text ? stringToToken(text) : SyntaxKind.Unknown; node.autoGenerateKind = GeneratedIdentifierKind.None; node.autoGenerateId = 0; - node.typeArguments = asNodeArray(typeArguments); + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } @@ -299,13 +284,13 @@ namespace ts { // Type Elements export function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature { - const propertySignature = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature; - propertySignature.modifiers = asNodeArray(modifiers); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; + const node = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature; + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; } export function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { @@ -2494,6 +2479,25 @@ namespace ts { /* @internal */ namespace ts { + export const nullTransformationContext: TransformationContext = { + enableEmitNotification: noop, + enableSubstitution: noop, + endLexicalEnvironment: () => undefined, + getCompilerOptions: notImplemented, + getEmitHost: notImplemented, + getEmitResolver: notImplemented, + hoistFunctionDeclaration: noop, + hoistVariableDeclaration: noop, + isEmitNotificationEnabled: notImplemented, + isSubstitutionEnabled: notImplemented, + onEmitNode: noop, + onSubstituteNode: notImplemented, + readEmitHelpers: notImplemented, + requestEmitHelper: noop, + resumeLexicalEnvironment: noop, + startLexicalEnvironment: noop, + suspendLexicalEnvironment: noop + }; // Compound nodes diff --git a/src/compiler/types.ts b/src/compiler/types.ts index df89120e441..e7e6f9ad1af 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -576,11 +576,11 @@ namespace ts { * If the identifier begins with two underscores, this will begin with three. */ text: string; - originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later + originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. - /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. - isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace - /*@internal*/ typeArguments?: NodeArray; // Only defined on synthesized nodes.Though not syntactically valid, used in emitting diagnostics. + /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. + isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace + /*@internal*/ typeArguments?: NodeArray; // Only defined on synthesized nodes.Though not syntactically valid, used in emitting diagnostics. } // Transient identifier node (marked by id === -1) @@ -2592,14 +2592,14 @@ namespace ts { SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type. // Error handling - allowThisInObjectLiteral = 1 << 10, - allowQualifedNameInPlaceOfIdentifier = 1 << 11, - allowTypeParameterInQualifiedName = 1 << 12, - allowAnonymousIdentifier = 1 << 13, - allowEmptyUnionOrIntersection = 1 << 14, - allowEmptyTuple = 1 << 15, + AllowThisInObjectLiteral = 1 << 10, + AllowQualifedNameInPlaceOfIdentifier = 1 << 11, + AllowTypeParameterInQualifiedName = 1 << 12, + AllowAnonymousIdentifier = 1 << 13, + AllowEmptyUnionOrIntersection = 1 << 14, + AllowEmptyTuple = 1 << 15, - ignoreErrors = allowThisInObjectLiteral | allowQualifedNameInPlaceOfIdentifier | allowTypeParameterInQualifiedName | allowAnonymousIdentifier | allowEmptyUnionOrIntersection | allowEmptyTuple, + ignoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowTypeParameterInQualifiedName | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple, // State inObjectTypeLiteral = 1 << 20, @@ -3538,8 +3538,7 @@ namespace ts { export const enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, - None = 2 + LineFeed = 1 } export interface LineAndCharacter { @@ -3964,7 +3963,6 @@ namespace ts { } export const enum EmitFlags { - None = 0, SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node. NoSubstitution = 1 << 2, // Disables further substitution of an expression. @@ -4195,7 +4193,7 @@ namespace ts { * the identifiers of the source file are used when generating unique names to avoid * collisions. */ - printNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined): string; + printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; /** * Prints a source file as-is, without any emit transformations. */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index be6b8ccee13..825465085c8 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3253,8 +3253,6 @@ namespace ts { const lineFeed = "\n"; export function getNewLineCharacter(options: CompilerOptions | PrinterOptions): string { switch (options.newLine) { - case NewLineKind.None: - return ""; case NewLineKind.CarriageReturnLineFeed: return carriageReturnLineFeed; case NewLineKind.LineFeed: diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index c9c3a3c48fa..c62af0da794 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -254,6 +254,7 @@ namespace ts { case SyntaxKind.Decorator: return updateDecorator(node, visitNode((node).expression, visitor, isExpression)); + // Type elements case SyntaxKind.PropertySignature: @@ -970,6 +971,15 @@ namespace ts { break; // Type member + + case SyntaxKind.PropertySignature: + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).questionToken, cbNode, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); + break; + case SyntaxKind.PropertyDeclaration: result = reduceNodes((node).decorators, cbNodes, result); result = reduceNodes((node).modifiers, cbNodes, result); @@ -978,6 +988,8 @@ namespace ts { result = reduceNode((node).initializer, cbNode, result); break; + case SyntaxKind.PropertySignature: + case SyntaxKind.MethodDeclaration: result = reduceNodes((node).decorators, cbNodes, result); result = reduceNodes((node).modifiers, cbNodes, result); diff --git a/src/services/services.ts b/src/services/services.ts index 43d875cbf7d..ccc9f66e51a 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -360,7 +360,7 @@ namespace ts { _incrementExpressionBrand: any; _unaryExpressionBrand: any; _expressionBrand: any; - typeArguments: any; + /*@internal*/typeArguments: NodeArray; constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) { super(pos, end); } From 9e9054bd2b112acfaa310fa7ac7cfb0209ff7c16 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 12 May 2017 17:42:10 -0700 Subject: [PATCH 188/282] handle todo --- src/compiler/checker.ts | 2 +- src/compiler/emitter.ts | 2 +- src/compiler/factory.ts | 12 ++---------- 3 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a4c5f401321..a5295df7b8b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2555,7 +2555,7 @@ namespace ts { const resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return createTypeLiteralNode(/*members*/ undefined); + return setEmitFlags(createTypeLiteralNode(/*members*/ undefined), EmitFlags.SingleLine); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 30e5ba1a091..8ec03e90c77 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -961,7 +961,7 @@ namespace ts { function emitTypeLiteral(node: TypeLiteralNode) { write("{"); - // TODO: fix added indentation so we can remove this check. + // If the literal is empty, do not add spaces between braces. if (node.members.length > 0) { emitList(node, node.members, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers); } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 45aa14bdd2b..d236ef99591 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3294,16 +3294,6 @@ namespace ts { return statements; } - export function parenthesizeConditionalHead(condition: Expression) { - const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken); - const emittedCondition = skipPartiallyEmittedExpressions(condition); - const conditionPrecedence = getExpressionPrecedence(emittedCondition); - if (compareValues(conditionPrecedence, conditionalPrecedence) === Comparison.LessThan) { - return createParen(condition); - } - return condition; - } - /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -3605,6 +3595,8 @@ namespace ts { return expression; } + function parenthesizeElementTypeMembers() {} + /** * Clones a series of not-emitted expressions with a new inner expression. * From 6fd86b47f9f374aeb8022f8a58cad877e503affb Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Fri, 12 May 2017 17:51:14 -0700 Subject: [PATCH 189/282] temp --- src/compiler/factory.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index d236ef99591..094ad8cb8cf 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3595,7 +3595,18 @@ namespace ts { return expression; } - function parenthesizeElementTypeMembers() {} + function parenthesizeElementTypeMember(member: TypeNode) { + switch (member.kind) { + case SyntaxKind.UnionType: + case SyntaxKind.IntersectionType: + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + return createParenthesizedType(member); + } + } + function parenthesizeElementTypeMembers(members: NodeArray) { + return createNodeArray(members.map(parenthesizeElementTypeMember)); + } /** * Clones a series of not-emitted expressions with a new inner expression. From 8af5910555460f1b96e7a13d289df78f0808d09b Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Mon, 15 May 2017 14:55:17 +0200 Subject: [PATCH 190/282] Only report used before declaration errors on regular enums const enums don't generate code and the values are inlined so now error is necessary --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 376bdc13c88..d6f56a69b9a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1280,7 +1280,7 @@ namespace ts { else if (result.flags & SymbolFlags.Class) { error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } - else if (result.flags & SymbolFlags.Enum) { + else if (result.flags & SymbolFlags.RegularEnum) { error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } } From 0cd2245c9ad125b0860c72c6058183ce84823ed0 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Mon, 15 May 2017 14:57:24 +0200 Subject: [PATCH 191/282] Accept baselines for const enum changes --- .../baselines/reference/enumUsedBeforeDeclaration.errors.txt | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt b/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt index aea5366389b..64e1830b521 100644 --- a/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt +++ b/tests/baselines/reference/enumUsedBeforeDeclaration.errors.txt @@ -1,14 +1,11 @@ tests/cases/compiler/enumUsedBeforeDeclaration.ts(1,18): error TS2450: Enum 'Color' used before its declaration. -tests/cases/compiler/enumUsedBeforeDeclaration.ts(2,24): error TS2450: Enum 'ConstColor' used before its declaration. -==== tests/cases/compiler/enumUsedBeforeDeclaration.ts (2 errors) ==== +==== tests/cases/compiler/enumUsedBeforeDeclaration.ts (1 errors) ==== const v: Color = Color.Green; ~~~~~ !!! error TS2450: Enum 'Color' used before its declaration. const v2: ConstColor = ConstColor.Green; - ~~~~~~~~~~ -!!! error TS2450: Enum 'ConstColor' used before its declaration. enum Color { Red, Green, Blue } const enum ConstColor { Red, Green, Blue } From 5eb2bd08acb4bf42e0aeb75f30dd90d83a4182fb Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 15 May 2017 08:24:29 -0700 Subject: [PATCH 192/282] findAllReferences: In `export default foo`, symbol name is `foo` --- src/compiler/utilities.ts | 4 ++++ src/services/importTracker.ts | 9 +++++---- .../fourslash/findAllRefsForDefaultExport04.ts | 16 ++++++++++++++++ 3 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsForDefaultExport04.ts diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 58a1822a24d..5046b44d094 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4032,6 +4032,10 @@ namespace ts { return node.kind === SyntaxKind.ExportSpecifier; } + export function isExportAssignment(node: Node): node is ExportAssignment { + return node.kind === SyntaxKind.ExportAssignment; + } + export function isModuleOrEnumDeclaration(node: Node): node is ModuleDeclaration | EnumDeclaration { return node.kind === SyntaxKind.ModuleDeclaration || node.kind === SyntaxKind.EnumDeclaration; } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index df50f3ec31c..c540c44620a 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -526,17 +526,18 @@ namespace ts.FindAllReferences { return isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol, exportKind } : undefined; } - function symbolName(symbol: Symbol): string { + function symbolName(symbol: Symbol): string | undefined { if (symbol.name !== "default") { return symbol.name; } - const name = forEach(symbol.declarations, decl => { + return forEach(symbol.declarations, decl => { + if (isExportAssignment(decl)) { + return isIdentifier(decl.expression) ? decl.expression.text : undefined; + } const name = getNameOfDeclaration(decl); return name && name.kind === SyntaxKind.Identifier && name.text; }); - Debug.assert(!!name); - return name; } /** If at an export specifier, go to the symbol it refers to. */ diff --git a/tests/cases/fourslash/findAllRefsForDefaultExport04.ts b/tests/cases/fourslash/findAllRefsForDefaultExport04.ts new file mode 100644 index 00000000000..c8fdb0a6149 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForDefaultExport04.ts @@ -0,0 +1,16 @@ +/// + +// @Filename: /a.ts +////const [|{| "isWriteAccess": true, "isDefinition": true |}a|] = 0; +////export default [|a|]; + +// @Filename: /b.ts +////import [|{| "isWriteAccess": true, "isDefinition": true |}a|] from "./a"; +////[|a|]; + +const [r0, r1, r2, r3] = test.ranges(); +verify.referenceGroups([r0, r1], [ + { definition: "const a: 0", ranges: [r0, r1] }, + { definition: "import a", ranges: [r2, r3] } +]); +verify.singleReferenceGroup("import a", [r2, r3]); From 26416c32f324395207659517a24a96de6a5a828c Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 10:17:36 -0700 Subject: [PATCH 193/282] Allow spreading arrays after required parameters This allows: 1. Spreading arrays into all-optional parameters whose types match. 2. Spreading arrays into parameter lists that are too short and whose body presumably uses `arguments`. --- src/compiler/checker.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dde60c19f4e..6c68df7c0c1 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9598,6 +9598,10 @@ namespace ts { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } + function areAllParametersOptionalAfter(signature: Signature, parameterIndex: number) { + return parameterIndex >= signature.minArgumentCount; + } + function isSupertypeOfEach(candidate: Type, types: Type[]): boolean { for (const t of types) { if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; @@ -14649,7 +14653,7 @@ namespace ts { // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || areAllParametersOptionalAfter(signature, spreadArgIndex); } // Too many arguments implies incorrect arity. From 20a4e32becf40823d86cdd76e32b5291e41315df Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 15 May 2017 10:18:34 -0700 Subject: [PATCH 194/282] parenthesization in factory --- src/compiler/checker.ts | 72 ++++++++++----------------------------- src/compiler/factory.ts | 29 ++++++++++++---- src/compiler/types.ts | 9 ++--- src/compiler/utilities.ts | 10 ++++++ 4 files changed, 52 insertions(+), 68 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a5295df7b8b..a7ca6769082 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2279,7 +2279,7 @@ namespace ts { } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors); + const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName); Debug.assert(typeNode !== undefined, "should always get typenode?"); const options = { removeComments: true }; const writer = createTextWriter(""); @@ -2360,10 +2360,8 @@ namespace ts { } function typeToTypeNodeHelper(type: Type, context: NodeBuilderContext): TypeNode { - const inElementType = context.flags & NodeBuilderFlags.InElementType; - const inFirstTypeArgument = context.flags & NodeBuilderFlags.InFirstTypeArgument; const inTypeAlias = context.flags & NodeBuilderFlags.InTypeAlias; - context.flags &= ~(NodeBuilderFlags.StateClearingFlags); + context.flags &= ~(NodeBuilderFlags.InTypeAlias); if (!type) { context.encounteredError = true; @@ -2443,15 +2441,15 @@ namespace ts { if (!inTypeAlias && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { const name = symbolToTypeReferenceName(type.aliasSymbol); - const typeArgumentNodes = toTypeArgumentNodes(type.aliasTypeArguments, context); + const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, context); return createTypeReferenceNode(name, typeArgumentNodes); } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; - const typeNodes = types && mapToTypeNodeArray(types, context, /*addInElementTypeFlag*/ true, /*addInFirstTypeArgumentFlag*/ false); + const typeNodes = types && mapToTypeNodeArray(types, context); if (typeNodes && typeNodes.length > 0) { const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); - return inElementType ? createParenthesizedType(unionOrIntersectionTypeNode) : unionOrIntersectionTypeNode; + return unionOrIntersectionTypeNode; } else { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { @@ -2467,15 +2465,11 @@ namespace ts { } if (type.flags & TypeFlags.Index) { const indexedType = (type).type; - context.flags |= NodeBuilderFlags.InElementType; const indexTypeNode = typeToTypeNodeHelper(indexedType, context); - Debug.assert(!(context.flags & NodeBuilderFlags.InElementType)); return createTypeOperatorNode(indexTypeNode); } if (type.flags & TypeFlags.IndexedAccess) { - context.flags |= NodeBuilderFlags.InElementType; const objectTypeNode = typeToTypeNodeHelper((type).objectType, context); - Debug.assert(!(context.flags & NodeBuilderFlags.InElementType)); const indexTypeNode = typeToTypeNodeHelper((type).indexType, context); return createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } @@ -2561,17 +2555,14 @@ namespace ts { if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); - return shouldAddParenthesisAroundFunctionType(signature, context) ? - createParenthesizedType(signatureNode) : - signatureNode; + return signatureNode; } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { const signature = resolved.constructSignatures[0]; const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context); - return shouldAddParenthesisAroundFunctionType(signature, context) ? - createParenthesizedType(signatureNode) : - signatureNode; + return signatureNode; } } @@ -2583,19 +2574,6 @@ namespace ts { return setEmitFlags(typeLiteralNode, EmitFlags.SingleLine); } - function shouldAddParenthesisAroundFunctionType(callSignature: Signature, context: NodeBuilderContext) { - if (inElementType) { - return true; - } - else if (inFirstTypeArgument) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - const typeParameters = callSignature.target && (context.flags & NodeBuilderFlags.WriteTypeArgumentsOfSignature) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function createTypeQueryNodeFromSymbol(symbol: Symbol, symbolFlags: SymbolFlags) { const entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return createTypeQueryNode(entityName); @@ -2615,15 +2593,13 @@ namespace ts { return createTypeReferenceNode("Array", [typeArgumentNode]); } - context.flags |= NodeBuilderFlags.InElementType; const elementType = typeToTypeNodeHelper(typeArguments[0], context); - Debug.assert(!(context.flags & NodeBuilderFlags.InElementType)); - return createArrayTypeNode(elementType); } else if (type.target.objectFlags & ObjectFlags.Tuple) { if (typeArguments.length > 0) { - const tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type)), context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ false); + const slice = typeArguments.slice(0, getTypeReferenceArity(type)); + const tupleConstituentNodes = slice && mapToTypeNodeArray(slice, context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return createTupleTypeNode(tupleConstituentNodes); } @@ -2649,7 +2625,8 @@ namespace ts { // 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 (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { - const typeArgumentNodes = createNodeArray(toTypeArgumentNodes(typeArguments.slice(start, i), context)); + const slice = typeArguments.slice(start, i); + const typeArgumentNodes = slice && createNodeArray(mapToTypeNodeArray(slice, context)); const namePart = symbolToTypeReferenceName(parent); (namePart.kind === SyntaxKind.Identifier ? namePart : namePart.right).typeArguments = typeArgumentNodes; @@ -2680,7 +2657,7 @@ namespace ts { if (some(typeArguments)) { const typeParameterCount = (type.target.typeParameters || emptyArray).length; const slice = typeArguments && typeArguments.slice(i, typeParameterCount); - typeArgumentNodes = toTypeArgumentNodes(slice, context); + typeArgumentNodes = slice && mapToTypeNodeArray(slice, context); } if (typeArgumentNodes) { @@ -2763,28 +2740,17 @@ namespace ts { } } - function mapToTypeNodeArray(types: Type[], context: NodeBuilderContext, addInElementTypeFlag: boolean, addInFirstTypeArgumentFlag: boolean): TypeNode[] { + function mapToTypeNodeArray(types: Type[], context: NodeBuilderContext): TypeNode[] { const result = []; - Debug.assert(!(context.flags & NodeBuilderFlags.InElementType), "should be unset at the beginning of the helper"); for (let i = 0; i < types.length; ++i) { const type = types[i]; - if (addInElementTypeFlag) { - context.flags |= NodeBuilderFlags.InElementType; - } - if (i === 0 && addInFirstTypeArgumentFlag) { - context.flags |= NodeBuilderFlags.InFirstTypeArgument; - } const typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); } } - Debug.assert(!(context.flags & NodeBuilderFlags.InElementType), "should be unset at the end of the helper"); - return result; - } - function toTypeArgumentNodes(typeArguments: Type[], context: NodeBuilderContext) { - return typeArguments && mapToTypeNodeArray(typeArguments, context, /*addInElementTypeFlag*/ false, /*addInFirstTypeArgumentFlag*/ true); + return result; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { @@ -2909,7 +2875,7 @@ namespace ts { Debug.assert(chain && 0 <= index && index < chain.length); const symbol = chain[index]; let typeParameterNodes: TypeNode[] | undefined; - if (index > 0) { + if (context.flags & NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { const parentSymbol = chain[index - 1]; let typeParameters: TypeParameter[]; if (getCheckFlags(symbol) & CheckFlags.Instantiated) { @@ -2921,11 +2887,9 @@ namespace ts { typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } + if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - typeParameterNodes = toTypeArgumentNodes(typeParameters, context); + typeParameterNodes = mapToTypeNodeArray(typeParameters, context); } } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 094ad8cb8cf..18e71f94ee3 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -506,7 +506,7 @@ namespace ts { export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) { const node = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode; node.typeName = asName(typeName); - node.typeArguments = asNodeArray(typeArguments); + node.typeArguments = typeArguments && parenthesizeTypeParameters(typeArguments); return node; } @@ -559,7 +559,7 @@ namespace ts { export function createArrayTypeNode(elementType: TypeNode) { const node = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode; - node.elementType = elementType; + node.elementType = parenthesizeElementTypeMember(elementType); return node; } @@ -599,7 +599,7 @@ namespace ts { export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) { const node = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode; - node.types = createNodeArray(types); + node.types = parenthesizeElementTypeMembers(types); return node; } @@ -628,7 +628,7 @@ namespace ts { export function createTypeOperatorNode(type: TypeNode) { const node = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode; node.operator = SyntaxKind.KeyOfKeyword; - node.type = type; + node.type = parenthesizeElementTypeMember(type); return node; } @@ -638,7 +638,7 @@ namespace ts { export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) { const node = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode; - node.objectType = objectType; + node.objectType = parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; } @@ -3595,7 +3595,7 @@ namespace ts { return expression; } - function parenthesizeElementTypeMember(member: TypeNode) { + export function parenthesizeElementTypeMember(member: TypeNode) { switch (member.kind) { case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: @@ -3603,11 +3603,26 @@ namespace ts { case SyntaxKind.ConstructorType: return createParenthesizedType(member); } + return member; } - function parenthesizeElementTypeMembers(members: NodeArray) { + + export function parenthesizeElementTypeMembers(members: TypeNode[]) { + // TODO: does this lose `originalNode` ptr? return createNodeArray(members.map(parenthesizeElementTypeMember)); } + export function parenthesizeTypeParameters(typeParameters: TypeNode[]) { + if (typeParameters && typeParameters.length > 0) { + const nodeArray = createNodeArray(typeParameters); + const firstEntry = nodeArray[0]; + if (isFunctionOrConstructor(firstEntry) && firstEntry.typeParameters) { + nodeArray[0] = createParenthesizedType(firstEntry); + } + + return nodeArray; + } + } + /** * Clones a series of not-emitted expressions with a new inner expression. * diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e7e6f9ad1af..cf204d158a1 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2590,25 +2590,20 @@ namespace ts { WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type. + WriteTypeParametersInQualifiedName = 1 << 9, // Error handling AllowThisInObjectLiteral = 1 << 10, AllowQualifedNameInPlaceOfIdentifier = 1 << 11, - AllowTypeParameterInQualifiedName = 1 << 12, AllowAnonymousIdentifier = 1 << 13, AllowEmptyUnionOrIntersection = 1 << 14, AllowEmptyTuple = 1 << 15, - ignoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowTypeParameterInQualifiedName | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple, + ignoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple, // State inObjectTypeLiteral = 1 << 20, - InElementType = 1 << 21, // Writing an array or union element type - InFirstTypeArgument = 1 << 22, // Writing first type argument of the instantiated type InTypeAlias = 1 << 23, // Writing type in type alias declaration - - /** Flags that should not be passed on to sub-nodes of the current node being built. */ - StateClearingFlags = InElementType | InFirstTypeArgument | InTypeAlias } export interface SymbolDisplayBuilder { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 825465085c8..80daf383639 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -881,6 +881,16 @@ namespace ts { return false; } + export function isFunctionOrConstructor(node: Node): node is FunctionTypeNode | ConstructorTypeNode { + switch (node.kind) { + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + return true; + } + + return false; + } + export function introducesArgumentsExoticObject(node: Node) { switch (node.kind) { case SyntaxKind.MethodDeclaration: From 9ba0668afafdbfd6d2a0212f4a2861bdb7a2124a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 10:20:28 -0700 Subject: [PATCH 195/282] Test:spread array after required params --- .../reference/callWithSpread2.errors.txt | 94 +++++++++++++++++++ tests/baselines/reference/callWithSpread2.js | 80 ++++++++++++++++ .../functionCalls/callWithSpread2.ts | 48 ++++++++++ 3 files changed, 222 insertions(+) create mode 100644 tests/baselines/reference/callWithSpread2.errors.txt create mode 100644 tests/baselines/reference/callWithSpread2.js create mode 100644 tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt new file mode 100644 index 00000000000..f12846ab1cd --- /dev/null +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -0,0 +1,94 @@ +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(40,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(41,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(42,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(43,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(44,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(45,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(46,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(46,11): error TS2461: Type '(a?: number, b?: number) => void' is not an array type. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(47,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(48,1): error TS2346: Supplied parameters do not match any signature of call target. + + +==== tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts (10 errors) ==== + // Desired semantics: take type of array that is spread, + // allow it to be applied to a + // *trailing* set of optional parameters whose types match. + // Length is *not* checked, the parameters it's applied to just have to be optional. + + // that means that tuples are non-starters because their array element type + // is a union like string | number. + + // with exceptions for JS functions that use arguments, or maybe all JS functions + + declare function all(a?: number, b?: number): void; + declare function weird(a?: number | string, b?: number | string): void; + declare function prefix(s: string, a?: number, b?: number): void; + declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; + declare function normal(s: string): void; + declare function thunk(): string; + + declare var ns: number[]; + declare var mixed: (number | string)[]; + declare var tuple: [number, string]; + + // good + all(...ns) + weird(...ns) + weird(...mixed) + weird(...tuple) + prefix("a", ...ns) + rest("d", ...ns) + + + // this covers the arguments case + normal("g", ...ns) + normal("h", ...mixed) + normal("i", ...tuple) + thunk(...ns) + thunk(...mixed) + thunk(...tuple) + + // bad + all(...mixed) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + all(...tuple) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + prefix("b", ...mixed) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + prefix("c", ...tuple) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + rest("e", ...mixed) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + rest("f", ...tuple) + ~~~~~~~~ +!!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. + prefix(...all) // required parameters are required + ~~~~~~~~~~~~~~ +!!! error TS2346: Supplied parameters do not match any signature of call target. + ~~~ +!!! error TS2461: Type '(a?: number, b?: number) => void' is not an array type. + prefix(...mixed) + ~~~~~~~~~~~~~~~~ +!!! error TS2346: Supplied parameters do not match any signature of call target. + prefix(...tuple) + ~~~~~~~~~~~~~~~~ +!!! error TS2346: Supplied parameters do not match any signature of call target. + \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread2.js b/tests/baselines/reference/callWithSpread2.js new file mode 100644 index 00000000000..25ccc582093 --- /dev/null +++ b/tests/baselines/reference/callWithSpread2.js @@ -0,0 +1,80 @@ +//// [callWithSpread2.ts] +// Desired semantics: take type of array that is spread, +// allow it to be applied to a +// *trailing* set of optional parameters whose types match. +// Length is *not* checked, the parameters it's applied to just have to be optional. + +// that means that tuples are non-starters because their array element type +// is a union like string | number. + +// with exceptions for JS functions that use arguments, or maybe all JS functions + +declare function all(a?: number, b?: number): void; +declare function weird(a?: number | string, b?: number | string): void; +declare function prefix(s: string, a?: number, b?: number): void; +declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; +declare function normal(s: string): void; +declare function thunk(): string; + +declare var ns: number[]; +declare var mixed: (number | string)[]; +declare var tuple: [number, string]; + +// good +all(...ns) +weird(...ns) +weird(...mixed) +weird(...tuple) +prefix("a", ...ns) +rest("d", ...ns) + + +// this covers the arguments case +normal("g", ...ns) +normal("h", ...mixed) +normal("i", ...tuple) +thunk(...ns) +thunk(...mixed) +thunk(...tuple) + +// bad +all(...mixed) +all(...tuple) +prefix("b", ...mixed) +prefix("c", ...tuple) +rest("e", ...mixed) +rest("f", ...tuple) +prefix(...all) // required parameters are required +prefix(...mixed) +prefix(...tuple) + + +//// [callWithSpread2.js] +// Desired semantics: take type of array that is spread, +// allow it to be applied to a +// *trailing* set of optional parameters whose types match. +// Length is *not* checked, the parameters it's applied to just have to be optional. +// good +all.apply(void 0, ns); +weird.apply(void 0, ns); +weird.apply(void 0, mixed); +weird.apply(void 0, tuple); +prefix.apply(void 0, ["a"].concat(ns)); +rest.apply(void 0, ["d"].concat(ns)); +// this covers the arguments case +normal.apply(void 0, ["g"].concat(ns)); +normal.apply(void 0, ["h"].concat(mixed)); +normal.apply(void 0, ["i"].concat(tuple)); +thunk.apply(void 0, ns); +thunk.apply(void 0, mixed); +thunk.apply(void 0, tuple); +// bad +all.apply(void 0, mixed); +all.apply(void 0, tuple); +prefix.apply(void 0, ["b"].concat(mixed)); +prefix.apply(void 0, ["c"].concat(tuple)); +rest.apply(void 0, ["e"].concat(mixed)); +rest.apply(void 0, ["f"].concat(tuple)); +prefix.apply(void 0, all); // required parameters are required +prefix.apply(void 0, mixed); +prefix.apply(void 0, tuple); diff --git a/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts new file mode 100644 index 00000000000..72ff97f7c90 --- /dev/null +++ b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts @@ -0,0 +1,48 @@ +// Desired semantics: take type of array that is spread, +// allow it to be applied to a +// *trailing* set of optional parameters whose types match. +// Length is *not* checked, the parameters it's applied to just have to be optional. + +// that means that tuples are non-starters because their array element type +// is a union like string | number. + +// with exceptions for JS functions that use arguments, or maybe all JS functions + +declare function all(a?: number, b?: number): void; +declare function weird(a?: number | string, b?: number | string): void; +declare function prefix(s: string, a?: number, b?: number): void; +declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; +declare function normal(s: string): void; +declare function thunk(): string; + +declare var ns: number[]; +declare var mixed: (number | string)[]; +declare var tuple: [number, string]; + +// good +all(...ns) +weird(...ns) +weird(...mixed) +weird(...tuple) +prefix("a", ...ns) +rest("d", ...ns) + + +// this covers the arguments case +normal("g", ...ns) +normal("h", ...mixed) +normal("i", ...tuple) +thunk(...ns) +thunk(...mixed) +thunk(...tuple) + +// bad +all(...mixed) +all(...tuple) +prefix("b", ...mixed) +prefix("c", ...tuple) +rest("e", ...mixed) +rest("f", ...tuple) +prefix(...all) // required parameters are required +prefix(...mixed) +prefix(...tuple) From b61eaf70a1587ad0d171ec3141ad90fe1a34d764 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 10:31:47 -0700 Subject: [PATCH 196/282] Inline function that is called once --- src/compiler/checker.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6c68df7c0c1..9e6a5f946b3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9598,10 +9598,6 @@ namespace ts { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } - function areAllParametersOptionalAfter(signature: Signature, parameterIndex: number) { - return parameterIndex >= signature.minArgumentCount; - } - function isSupertypeOfEach(candidate: Type, types: Type[]): boolean { for (const t of types) { if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; @@ -14653,7 +14649,7 @@ namespace ts { // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || areAllParametersOptionalAfter(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. From 4c80aa17b3e1f04283f821638b90f6daf679b237 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 10:38:51 -0700 Subject: [PATCH 197/282] Clean up comments in tests --- .../reference/callWithSpread2.errors.txt | 30 +++++++------------ tests/baselines/reference/callWithSpread2.js | 14 --------- .../functionCalls/callWithSpread2.ts | 10 ------- 3 files changed, 10 insertions(+), 44 deletions(-) diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt index f12846ab1cd..770e33c9ae9 100644 --- a/tests/baselines/reference/callWithSpread2.errors.txt +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -1,32 +1,22 @@ -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(40,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(30,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(41,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(31,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(42,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(32,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(43,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(33,13): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(44,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(45,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(35,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(46,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(46,11): error TS2461: Type '(a?: number, b?: number) => void' is not an array type. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(47,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(48,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,11): error TS2461: Type '(a?: number, b?: number) => void' is not an array type. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(37,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(38,1): error TS2346: Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts (10 errors) ==== - // Desired semantics: take type of array that is spread, - // allow it to be applied to a - // *trailing* set of optional parameters whose types match. - // Length is *not* checked, the parameters it's applied to just have to be optional. - - // that means that tuples are non-starters because their array element type - // is a union like string | number. - - // with exceptions for JS functions that use arguments, or maybe all JS functions - declare function all(a?: number, b?: number): void; declare function weird(a?: number | string, b?: number | string): void; declare function prefix(s: string, a?: number, b?: number): void; diff --git a/tests/baselines/reference/callWithSpread2.js b/tests/baselines/reference/callWithSpread2.js index 25ccc582093..0380c69f80f 100644 --- a/tests/baselines/reference/callWithSpread2.js +++ b/tests/baselines/reference/callWithSpread2.js @@ -1,14 +1,4 @@ //// [callWithSpread2.ts] -// Desired semantics: take type of array that is spread, -// allow it to be applied to a -// *trailing* set of optional parameters whose types match. -// Length is *not* checked, the parameters it's applied to just have to be optional. - -// that means that tuples are non-starters because their array element type -// is a union like string | number. - -// with exceptions for JS functions that use arguments, or maybe all JS functions - declare function all(a?: number, b?: number): void; declare function weird(a?: number | string, b?: number | string): void; declare function prefix(s: string, a?: number, b?: number): void; @@ -50,10 +40,6 @@ prefix(...tuple) //// [callWithSpread2.js] -// Desired semantics: take type of array that is spread, -// allow it to be applied to a -// *trailing* set of optional parameters whose types match. -// Length is *not* checked, the parameters it's applied to just have to be optional. // good all.apply(void 0, ns); weird.apply(void 0, ns); diff --git a/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts index 72ff97f7c90..07441dc74bf 100644 --- a/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts +++ b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts @@ -1,13 +1,3 @@ -// Desired semantics: take type of array that is spread, -// allow it to be applied to a -// *trailing* set of optional parameters whose types match. -// Length is *not* checked, the parameters it's applied to just have to be optional. - -// that means that tuples are non-starters because their array element type -// is a union like string | number. - -// with exceptions for JS functions that use arguments, or maybe all JS functions - declare function all(a?: number, b?: number): void; declare function weird(a?: number | string, b?: number | string): void; declare function prefix(s: string, a?: number, b?: number): void; From cefcc668a881a52b71db6e601ba70c00f1c36332 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 10:55:58 -0700 Subject: [PATCH 198/282] Correct test argument in callwithSpread2 --- tests/baselines/reference/callWithSpread2.errors.txt | 9 +++------ tests/baselines/reference/callWithSpread2.js | 4 ++-- .../expressions/functionCalls/callWithSpread2.ts | 2 +- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt index 770e33c9ae9..cfea427a2a7 100644 --- a/tests/baselines/reference/callWithSpread2.errors.txt +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -11,12 +11,11 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,11): err tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(35,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,11): error TS2461: Type '(a?: number, b?: number) => void' is not an array type. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(37,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(38,1): error TS2346: Supplied parameters do not match any signature of call target. -==== tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts (10 errors) ==== +==== tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts (9 errors) ==== declare function all(a?: number, b?: number): void; declare function weird(a?: number | string, b?: number | string): void; declare function prefix(s: string, a?: number, b?: number): void; @@ -70,11 +69,9 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(38,1): erro ~~~~~~~~ !!! error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. !!! error TS2345: Type 'string' is not assignable to type 'number'. - prefix(...all) // required parameters are required - ~~~~~~~~~~~~~~ + prefix(...ns) // required parameters are required + ~~~~~~~~~~~~~ !!! error TS2346: Supplied parameters do not match any signature of call target. - ~~~ -!!! error TS2461: Type '(a?: number, b?: number) => void' is not an array type. prefix(...mixed) ~~~~~~~~~~~~~~~~ !!! error TS2346: Supplied parameters do not match any signature of call target. diff --git a/tests/baselines/reference/callWithSpread2.js b/tests/baselines/reference/callWithSpread2.js index 0380c69f80f..55296d924f7 100644 --- a/tests/baselines/reference/callWithSpread2.js +++ b/tests/baselines/reference/callWithSpread2.js @@ -34,7 +34,7 @@ prefix("b", ...mixed) prefix("c", ...tuple) rest("e", ...mixed) rest("f", ...tuple) -prefix(...all) // required parameters are required +prefix(...ns) // required parameters are required prefix(...mixed) prefix(...tuple) @@ -61,6 +61,6 @@ prefix.apply(void 0, ["b"].concat(mixed)); prefix.apply(void 0, ["c"].concat(tuple)); rest.apply(void 0, ["e"].concat(mixed)); rest.apply(void 0, ["f"].concat(tuple)); -prefix.apply(void 0, all); // required parameters are required +prefix.apply(void 0, ns); // required parameters are required prefix.apply(void 0, mixed); prefix.apply(void 0, tuple); diff --git a/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts index 07441dc74bf..9151f52f00d 100644 --- a/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts +++ b/tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts @@ -33,6 +33,6 @@ prefix("b", ...mixed) prefix("c", ...tuple) rest("e", ...mixed) rest("f", ...tuple) -prefix(...all) // required parameters are required +prefix(...ns) // required parameters are required prefix(...mixed) prefix(...tuple) From d8f29a5fe8b918c2a48e7b745117de3c66b5a827 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 15 May 2017 12:42:28 -0700 Subject: [PATCH 199/282] update tests --- ...assImplementInterfaceMemberNestedTypeAlias.ts | 16 ++++++++++++++++ ...eFixClassImplementInterfaceMemberTypeAlias.ts | 4 ++-- 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/codeFixClassImplementInterfaceMemberNestedTypeAlias.ts diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberNestedTypeAlias.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberNestedTypeAlias.ts new file mode 100644 index 00000000000..5aa5f1a4e51 --- /dev/null +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberNestedTypeAlias.ts @@ -0,0 +1,16 @@ +/// + +//// type Either = { val: T } | Error; +//// interface I { +//// x: Either>; +//// foo(x: Either>): void; +//// } +//// class C implements I {[| |]} + +verify.rangeAfterCodeFix(` + x: Either>; + foo(x: Either>): void { + throw new Error("Method not implemented."); + } +`); + diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts index f7dfd5e1787..44981302a1a 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMemberTypeAlias.ts @@ -1,12 +1,12 @@ /// //// type MyType = [string, number]; -//// interface I { test(a: MyType): void; } +//// interface I { x: MyType; test(a: MyType): void; } //// class C implements I {[| |]} verify.rangeAfterCodeFix(` + x: [string, number]; test(a: [string, number]): void { throw new Error("Method not implemented."); } `); - From 38784b761ae017e399e373bdaceee637790cd234 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 12 May 2017 08:33:31 -0700 Subject: [PATCH 200/282] Support for JSDoc in services --- src/compiler/binder.ts | 2 +- src/compiler/checker.ts | 5 ++++ src/compiler/parser.ts | 2 +- src/compiler/utilities.ts | 23 +++++++++----- src/harness/fourslash.ts | 14 +++++---- src/harness/harness.ts | 4 +-- src/services/breakpoints.ts | 2 +- .../codefixes/disableJsDiagnostics.ts | 2 +- src/services/codefixes/fixAddMissingMember.ts | 2 +- ...sDoesntImplementInheritedAbstractMember.ts | 2 +- .../fixClassIncorrectlyImplementsInterface.ts | 2 +- .../fixClassSuperMustPrecedeThisAccess.ts | 2 +- .../fixConstructorForDerivedNeedSuperCall.ts | 2 +- .../fixExtendsInterfaceBecomesImplements.ts | 2 +- .../fixForgottenThisPropertyAccess.ts | 2 +- src/services/codefixes/fixSpelling.ts | 2 +- src/services/codefixes/importFixes.ts | 2 +- .../codefixes/unusedIdentifierFixes.ts | 12 ++++---- src/services/completions.ts | 4 +-- src/services/documentHighlights.ts | 2 +- src/services/findAllReferences.ts | 25 +++++++++------- src/services/formatting/formatting.ts | 2 +- src/services/goToDefinition.ts | 4 +-- src/services/jsDoc.ts | 2 +- src/services/pathCompletions.ts | 2 +- src/services/services.ts | 29 +++++++++++------- src/services/textChanges.ts | 6 ++-- src/services/utilities.ts | 30 +++++++++---------- .../fourslash/findAllRefsPrimitiveJsDoc.ts | 11 +++++++ ...currencesIsDefinitionOfComputedProperty.ts | 2 +- .../fourslash/jsDocGoToImplementation.ts | 10 +++++++ tests/cases/fourslash/jsDocServices.ts | 24 +++++++++++++++ 32 files changed, 156 insertions(+), 81 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsPrimitiveJsDoc.ts create mode 100644 tests/cases/fourslash/jsDocGoToImplementation.ts create mode 100644 tests/cases/fourslash/jsDocServices.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index b6074162fff..4292b06e775 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -603,7 +603,7 @@ namespace ts { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (isInJavaScriptFile(node) && node.jsDoc) { + if (node.jsDoc) { forEach(node.jsDoc, bind); } if (checkUnreachable(node)) { diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 64a4095162b..e1bd629c7b4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22213,6 +22213,11 @@ namespace ts { } } + if (entityName.parent!.kind === SyntaxKind.JSDocParameterTag) { + const parameter = ts.getParameterFromJSDoc(entityName.parent as JSDocParameterTag); + return parameter && parameter.symbol; + } + if (isPartOfExpression(entityName)) { if (nodeIsMissing(entityName)) { // Missing entity name. diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index cc3fb24bdb8..4393dc74c98 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -50,7 +50,7 @@ namespace ts { // stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, // 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. - export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { + export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: NodeArray) => T): T { if (!node) { return; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5725d04a9cf..75ff89dd645 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1591,7 +1591,7 @@ namespace ts { // Pull parameter comments from declaring function as well if (node.kind === SyntaxKind.Parameter) { - cache = concatenate(cache, getJSDocParameterTags(node)); + cache = concatenate(cache, getJSDocParameterTags(node as ParameterDeclaration)); } if (isVariableLike(node) && node.initializer) { @@ -1602,11 +1602,8 @@ namespace ts { } } - export function getJSDocParameterTags(param: Node): JSDocParameterTag[] { - if (!isParameter(param)) { - return undefined; - } - const func = param.parent as FunctionLikeDeclaration; + export function getJSDocParameterTags(param: ParameterDeclaration): JSDocParameterTag[] { + const func = param.parent; const tags = getJSDocTags(func, SyntaxKind.JSDocParameterTag) as JSDocParameterTag[]; if (!param.name) { // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification @@ -1627,10 +1624,22 @@ namespace ts { } } + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + export function getParameterFromJSDoc(node: JSDocParameterTag): ParameterDeclaration | undefined { + const name = node.parameterName.text; + const grandParent = node.parent!.parent!; + Debug.assert(node.parent!.kind === SyntaxKind.JSDocComment); + if (!isFunctionLike(grandParent)) { + return undefined; + } + return find(grandParent.parameters, p => + p.name.kind === SyntaxKind.Identifier && p.name.text === name); + } + export function getJSDocType(node: Node): JSDocType { let tag: JSDocTypeTag | JSDocParameterTag = getFirstJSDocTag(node, SyntaxKind.JSDocTypeTag) as JSDocTypeTag; if (!tag && node.kind === SyntaxKind.Parameter) { - const paramTags = getJSDocParameterTags(node); + const paramTags = getJSDocParameterTags(node as ParameterDeclaration); if (paramTags) { tag = find(paramTags, tag => !!tag.typeExpression); } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 83d27c951be..ceb6bf16a56 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -916,7 +916,7 @@ namespace FourSlash { } private getNode(): ts.Node { - return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition); + return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition, /*includeJsDocComment*/ false); } private goToAndGetNode(range: Range): ts.Node { @@ -994,17 +994,15 @@ namespace FourSlash { } public verifyReferenceGroups(startRanges: Range | Range[], parts: Array<{ definition: string, ranges: Range[] }>): void { - interface ReferenceJson { definition: string; ranges: ts.ReferenceEntry[]; } - type ReferencesJson = ReferenceJson[]; - const fullExpected = parts.map(({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) })); + const fullExpected = ts.map(parts, ({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) })); for (const startRange of toArray(startRanges)) { this.goToRangeStart(startRange); - const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }) => ({ + const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }) => ({ definition: definition.displayParts.map(d => d.text).join(""), ranges: references })); - this.assertObjectsEqual(fullActual, fullExpected); + this.assertObjectsEqual(fullActual, fullExpected); } function rangeToReferenceEntry(r: Range): ts.ReferenceEntry { @@ -1047,6 +1045,10 @@ namespace FourSlash { this.raiseError(`${msgPrefix}At ${path}: ${msg}`); }; + if ((actual === undefined) !== (expected === undefined)) { + fail(`Expected ${expected}, got ${actual}`); + } + for (const key in actual) if (ts.hasProperty(actual as any, key)) { const ak = actual[key], ek = expected[key]; if (typeof ak === "object" && typeof ek === "object") { diff --git a/src/harness/harness.ts b/src/harness/harness.ts index c0ef2672b27..b46d7652e1d 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -172,7 +172,7 @@ namespace Utils { assert.isFalse(child.pos < currentPos, "child.pos < currentPos"); currentPos = child.end; }, - (array: ts.NodeArray) => { + array => { assert.isFalse(array.pos < node.pos, "array.pos < node.pos"); assert.isFalse(array.end > node.end, "array.end > node.end"); assert.isFalse(array.pos < currentPos, "array.pos < currentPos"); @@ -383,7 +383,7 @@ namespace Utils { assertStructuralEquals(child1, child2); }, - (array1: ts.NodeArray) => { + array1 => { const childName = findChildName(node1, array1); const array2: ts.NodeArray = (node2)[childName]; diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index e47f6d016c7..38da43bdee8 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -14,7 +14,7 @@ namespace ts.BreakpointResolver { return undefined; } - let tokenAtLocation = getTokenAtPosition(sourceFile, position); + let tokenAtLocation = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 7fa5c5bf23f..b5f9e5587a3 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -22,7 +22,7 @@ namespace ts.codefix { // We also want to check if the previous line holds a comment for a node on the next line // if so, we do not want to separate the node from its comment if we can. if (!isInComment(sourceFile, startPosition) && !isInString(sourceFile, startPosition) && !isInTemplateString(sourceFile, startPosition)) { - const token = getTouchingToken(sourceFile, startPosition); + const token = getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); const tokenLeadingCommnets = getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 346cdaaaf19..64e7e560094 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -13,7 +13,7 @@ namespace ts.codefix { // This is the identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.Identifier) { return undefined; diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index 62f89b1a21a..768eaf752b7 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -15,7 +15,7 @@ namespace ts.codefix { const start = context.span.start; // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); const checker = context.program.getTypeChecker(); if (isClassLike(token.parent)) { diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 3b1b99febb0..bed9621b729 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -8,7 +8,7 @@ namespace ts.codefix { function getActionForClassLikeIncorrectImplementsInterface(context: CodeFixContext): CodeAction[] | undefined { const sourceFile = context.sourceFile; const start = context.span.start; - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); const checker = context.program.getTypeChecker(); const classDeclaration = getContainingClass(token); diff --git a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts index 2217dda8b0c..56128be9d07 100644 --- a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts +++ b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts @@ -5,7 +5,7 @@ namespace ts.codefix { getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.ThisKeyword) { return undefined; } diff --git a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts index 822c34842fd..517a79e39bd 100644 --- a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts +++ b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts @@ -4,7 +4,7 @@ namespace ts.codefix { errorCodes: [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.ConstructorKeyword) { return undefined; diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 80d4345a943..d23f61d0f92 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -5,7 +5,7 @@ namespace ts.codefix { getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; const start = context.span.start; - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); const classDeclNode = getContainingClass(token); if (!(token.kind === SyntaxKind.Identifier && isClassLike(classDeclNode))) { return undefined; diff --git a/src/services/codefixes/fixForgottenThisPropertyAccess.ts b/src/services/codefixes/fixForgottenThisPropertyAccess.ts index 711a3289a27..6925b557755 100644 --- a/src/services/codefixes/fixForgottenThisPropertyAccess.ts +++ b/src/services/codefixes/fixForgottenThisPropertyAccess.ts @@ -4,7 +4,7 @@ namespace ts.codefix { errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== SyntaxKind.Identifier) { return undefined; } diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts index b58dab95002..c8f539e8d34 100644 --- a/src/services/codefixes/fixSpelling.ts +++ b/src/services/codefixes/fixSpelling.ts @@ -12,7 +12,7 @@ namespace ts.codefix { // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - const node = getTokenAtPosition(sourceFile, context.span.start); + const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 const checker = context.program.getTypeChecker(); let suggestion: string; if (node.kind === SyntaxKind.Identifier && isPropertyAccessExpression(node.parent)) { diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index aaf7b535add..7ca57c2a69f 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -128,7 +128,7 @@ namespace ts.codefix { const allSourceFiles = context.program.getSourceFiles(); const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - const token = getTokenAtPosition(sourceFile, context.span.start); + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); const name = token.getText(); const symbolIdActionMap = new ImportCodeActionMap(); diff --git a/src/services/codefixes/unusedIdentifierFixes.ts b/src/services/codefixes/unusedIdentifierFixes.ts index 422a28098a6..5d85979fcf9 100644 --- a/src/services/codefixes/unusedIdentifierFixes.ts +++ b/src/services/codefixes/unusedIdentifierFixes.ts @@ -9,11 +9,11 @@ namespace ts.codefix { const sourceFile = context.sourceFile; const start = context.span.start; - let token = getTokenAtPosition(sourceFile, start); + let token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); // this handles var ["computed"] = 12; if (token.kind === SyntaxKind.OpenBracketToken) { - token = getTokenAtPosition(sourceFile, start + 1); + token = getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); } switch (token.kind) { @@ -48,11 +48,11 @@ namespace ts.codefix { case SyntaxKind.TypeParameter: const typeParameters = (token.parent.parent).typeParameters; if (typeParameters.length === 1) { - const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1); + const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); if (!previousToken || previousToken.kind !== SyntaxKind.LessThanToken) { return deleteRange(typeParameters); } - const nextToken = getTokenAtPosition(sourceFile, typeParameters.end); + const nextToken = getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); if (!nextToken || nextToken.kind !== SyntaxKind.GreaterThanToken) { return deleteRange(typeParameters); } @@ -99,7 +99,7 @@ namespace ts.codefix { else { // import |d,| * as ns from './file' const start = importClause.name.getStart(sourceFile); - const nextToken = getTokenAtPosition(sourceFile, importClause.name.end); + const nextToken = getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); if (nextToken && nextToken.kind === SyntaxKind.CommaToken) { // shift first non-whitespace position after comma to the start position of the node return deleteRange({ pos: start, end: skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); @@ -116,7 +116,7 @@ namespace ts.codefix { return deleteNode(importDecl); } else { - const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false); if (previousToken && previousToken.kind === SyntaxKind.CommaToken) { const startPosition = textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, textChanges.Position.FullStart); return deleteRange({ pos: startPosition, end: namespaceImport.end }); diff --git a/src/services/completions.ts b/src/services/completions.ts index 318c02683ff..734402514c9 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -346,7 +346,7 @@ namespace ts.Completions { let requestJsDocTag = false; let start = timestamp(); - const currentToken = getTokenAtPosition(sourceFile, position); + const currentToken = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 log("getCompletionData: Get current token: " + (timestamp() - start)); start = timestamp(); @@ -441,7 +441,7 @@ namespace ts.Completions { let isRightOfOpenTag = false; let isStartingCloseTag = false; - let location = getTouchingPropertyName(sourceFile, position); + let location = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index a8afc46d736..5f15b887924 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -1,7 +1,7 @@ /* @internal */ namespace ts.DocumentHighlights { export function getDocumentHighlights(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 395c282f6d5..16a516c2603 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -60,15 +60,19 @@ namespace ts.FindAllReferences { } export function getImplementationsAtPosition(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] { - const node = getTouchingPropertyName(sourceFile, position); + // A node in a JSDoc comment can't have an implementation anyway. + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); const referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } function getImplementationReferenceEntries(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined { + if (node.parent.kind === SyntaxKind.SourceFile) { + return undefined; + } // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { + else if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { const result: NodeEntry[] = []; Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, node => result.push(nodeEntry(node))); return result; @@ -680,7 +684,7 @@ namespace ts.FindAllReferences.Core { const labelName = targetLabel.text; const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (const position of possiblePositions) { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); // Only pick labels that are either the target label, or have a target that is the target label if (node && (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel))) { references.push(nodeEntry(node)); @@ -718,9 +722,10 @@ namespace ts.FindAllReferences.Core { } function addReferencesForKeywordInFile(sourceFile: SourceFile, kind: SyntaxKind, searchText: string, references: Push): void { - const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); + // Want fullStart so we can find the symbol in JSDoc comments + const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, /*fullStart*/ true); for (const position of possiblePositions) { - const referenceLocation = getTouchingPropertyName(sourceFile, position); + const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (referenceLocation.kind === kind) { references.push(nodeEntry(referenceLocation)); } @@ -742,13 +747,13 @@ namespace ts.FindAllReferences.Core { return; } - for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments)) { + for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments || container.jsDoc !== undefined)) { getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile: SourceFile, position: number, search: Search, state: State): void { - const referenceLocation = getTouchingPropertyName(sourceFile, position); + const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { // This wasn't the start of a token. Check to see if it might be a @@ -1188,7 +1193,7 @@ namespace ts.FindAllReferences.Core { const sourceFile = searchSpaceNode.getSourceFile(); const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); for (const position of possiblePositions) { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== SyntaxKind.SuperKeyword) { continue; @@ -1265,7 +1270,7 @@ namespace ts.FindAllReferences.Core { function getThisReferencesInFile(sourceFile: SourceFile, searchSpaceNode: Node, possiblePositions: number[], result: Entry[]): void { forEach(possiblePositions, position => { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || !isThis(node)) { return; } @@ -1319,7 +1324,7 @@ namespace ts.FindAllReferences.Core { function getReferencesForStringLiteralInFile(sourceFile: SourceFile, searchText: string, possiblePositions: number[], references: Push): void { for (const position of possiblePositions) { - const node = getTouchingWord(sourceFile, position); + const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (node && node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).text === searchText) { references.push(nodeEntry(node, /*isInString*/ true)); } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index d5bd33e33cc..531b768f6d8 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -599,7 +599,7 @@ namespace ts.formatting { child => { processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, - (nodes: NodeArray) => { + nodes => { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 07b1e4448bd..bc669a6d200 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -19,7 +19,7 @@ namespace ts.GoToDefinition { [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - const node = getTouchingPropertyName(sourceFile, position); + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -104,7 +104,7 @@ namespace ts.GoToDefinition { /// Goto type export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] { - const node = getTouchingPropertyName(sourceFile, position); + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 4422aab7156..b130a7f754b 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -158,7 +158,7 @@ namespace ts.JsDoc { return undefined; } - const tokenAtPos = getTokenAtPosition(sourceFile, position); + const tokenAtPos = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); const tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 2b45457c147..58de3ec8137 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -283,7 +283,7 @@ namespace ts.Completions.PathCompletions { } export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): CompletionInfo { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return undefined; } diff --git a/src/services/services.ts b/src/services/services.ts index 1b4678b5dbc..732d54427ba 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -105,6 +105,7 @@ namespace ts { scanner.setTextPos(pos); while (pos < end) { const token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); + Debug.assert(token !== SyntaxKind.EndOfFileToken); // Else it would infinitely loop const textPos = scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -133,10 +134,15 @@ namespace ts { } private createChildren(sourceFile?: SourceFileLike) { - let children: Node[]; - if (this.kind >= SyntaxKind.FirstNode) { + if (isJSDocTag(this)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + const children: Node[] = []; + this.forEachChild(child => { children.push(child); }); + this._children = children; + } + else if (this.kind >= SyntaxKind.FirstNode) { + const children: Node[] = []; scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; let pos = this.pos; const useJSDocScanner = this.kind >= SyntaxKind.FirstJSDocTagNode && this.kind <= SyntaxKind.LastJSDocTagNode; const processNode = (node: Node) => { @@ -153,7 +159,7 @@ namespace ts { if (pos < nodes.pos) { pos = this.addSyntheticNodes(children, pos, nodes.pos, useJSDocScanner); } - children.push(this.createSyntaxList(>nodes)); + children.push(this.createSyntaxList(nodes)); pos = nodes.end; }; // jsDocComments need to be the first children @@ -171,8 +177,11 @@ namespace ts { this.addSyntheticNodes(children, pos, this.end); } scanner.setText(undefined); + this._children = children; + } + else { + this._children = emptyArray; } - this._children = children || emptyArray; } public getChildCount(sourceFile?: SourceFile): number { @@ -213,7 +222,7 @@ namespace ts { return child.kind < SyntaxKind.FirstNode ? child : child.getLastToken(sourceFile); } - public forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { + public forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: NodeArray) => T): T { return forEachChild(this, cbNode, cbNodeArray); } } @@ -1353,7 +1362,7 @@ namespace ts { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); - const node = getTouchingPropertyName(sourceFile, position); + const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -1540,7 +1549,7 @@ namespace ts { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - const node = getTouchingPropertyName(sourceFile, startPos); + const node = getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { return; @@ -1651,7 +1660,7 @@ namespace ts { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const result: TextSpan[] = []; - const token = getTouchingToken(sourceFile, position); + const token = getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); if (token.getStart(sourceFile) === position) { const matchKind = getMatchingTokenKind(token); @@ -1853,7 +1862,7 @@ namespace ts { // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - const token = getTokenAtPosition(sourceFile, matchPosition); + const token = getTokenAtPosition(sourceFile, matchPosition, /*includeJsDocComment*/ false); if (!isInsideComment(sourceFile, token, matchPosition)) { continue; } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 7ff0c37fa93..c82a28953c7 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -202,7 +202,7 @@ namespace ts.textChanges { return this; } if (index !== containingList.length - 1) { - const nextToken = getTokenAtPosition(sourceFile, node.end); + const nextToken = getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { // find first non-whitespace position in the leading trivia of the node const startPosition = skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -214,7 +214,7 @@ namespace ts.textChanges { } } else { - const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end); + const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -292,7 +292,7 @@ namespace ts.textChanges { if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - const nextToken = getTokenAtPosition(sourceFile, after.end); + const nextToken = getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 4ae9204f7ed..cf46df3708e 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -621,29 +621,29 @@ namespace ts { /* Gets the token whose text has range [start, end) and * position >= start and (position < end or (position === end && token is keyword or identifier)) */ - export function getTouchingWord(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node { - return getTouchingToken(sourceFile, position, n => isWord(n.kind), includeJsDocComment); + export function getTouchingWord(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node { + return getTouchingToken(sourceFile, position, includeJsDocComment, n => isWord(n.kind)); } /* Gets the token whose text has range [start, end) and position >= start * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) */ - export function getTouchingPropertyName(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node { - return getTouchingToken(sourceFile, position, n => isPropertyName(n.kind), includeJsDocComment); + export function getTouchingPropertyName(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node { + return getTouchingToken(sourceFile, position, includeJsDocComment, n => isPropertyName(n.kind)); } /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - export function getTouchingToken(sourceFile: SourceFile, position: number, includeItemAtEndPosition?: (n: Node) => boolean, includeJsDocComment = false): Node { + export function getTouchingToken(sourceFile: SourceFile, position: number, includeJsDocComment: boolean, includeItemAtEndPosition?: (n: Node) => boolean): Node { return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); } /** Returns a token if position is in [start-of-leading-trivia, end) */ - export function getTokenAtPosition(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node { + export function getTokenAtPosition(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node { return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); } /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean, includeJsDocComment = false): Node { + function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean, includeJsDocComment: boolean): Node { let current: Node = sourceFile; outer: while (true) { if (isToken(current)) { @@ -708,7 +708,7 @@ namespace ts { export function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - const tokenAtPosition = getTokenAtPosition(file, position); + const tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -842,7 +842,7 @@ namespace ts { * returns true if the position is in between the open and close elements of an JSX expression. */ export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return false; @@ -878,7 +878,7 @@ namespace ts { } export function isInTemplateString(sourceFile: SourceFile, position: number) { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } @@ -886,8 +886,8 @@ namespace ts { * Returns true if the cursor at position in sourceFile is within a comment that additionally * satisfies predicate, and false otherwise. */ - export function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean { - const token = getTokenAtPosition(sourceFile, position); + function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean { + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (token && position <= token.getStart(sourceFile)) { const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); @@ -914,7 +914,7 @@ namespace ts { } export function hasDocComment(sourceFile: SourceFile, position: number) { - const token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); @@ -931,7 +931,7 @@ namespace ts { * Get the corresponding JSDocTag node if the position is in a jsDoc comment */ export function getJsDocTagAtPosition(sourceFile: SourceFile, position: number): JSDocTag { - let node = ts.getTokenAtPosition(sourceFile, position); + let node = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (isToken(node)) { switch (node.kind) { case SyntaxKind.VarKeyword: @@ -1398,6 +1398,6 @@ namespace ts { } export function getOpenBraceOfClassLike(declaration: ClassLikeDeclaration, sourceFile: SourceFile) { - return getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } } diff --git a/tests/cases/fourslash/findAllRefsPrimitiveJsDoc.ts b/tests/cases/fourslash/findAllRefsPrimitiveJsDoc.ts new file mode 100644 index 00000000000..82daf720d19 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsPrimitiveJsDoc.ts @@ -0,0 +1,11 @@ +// @noLib: true + +/// + +/////** +//// * @param {[|number|]} n +//// * @returns {[|number|]} +//// */ +////function f(n: [|number|]): [|number|] {} + +verify.singleReferenceGroup("number"); diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts index 27c34e56600..7d6cb0a48af 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts @@ -6,4 +6,4 @@ const ranges = test.ranges(); const [r0, r1, r2] = ranges; verify.referenceGroups(r0, [{ definition: '(property) ["foo"]: number', ranges }]); -verify.referenceGroups([r1, r2], []); // TODO: fix +verify.referenceGroups([r1, r2], undefined); // TODO: fix diff --git a/tests/cases/fourslash/jsDocGoToImplementation.ts b/tests/cases/fourslash/jsDocGoToImplementation.ts new file mode 100644 index 00000000000..cad5c29c82f --- /dev/null +++ b/tests/cases/fourslash/jsDocGoToImplementation.ts @@ -0,0 +1,10 @@ +/// + +/////** +//// * @param /**/[|foo|] I pity the foo +//// */ +////function f([|foo|]: number) { +//// return foo; +////} + +verify.allRangesAppearInImplementationList(""); diff --git a/tests/cases/fourslash/jsDocServices.ts b/tests/cases/fourslash/jsDocServices.ts new file mode 100644 index 00000000000..df1e985f876 --- /dev/null +++ b/tests/cases/fourslash/jsDocServices.ts @@ -0,0 +1,24 @@ +/// + +// Note: We include the word "foo" in the documentation to test for a bug where +// the `.getChildren()` of the JSDocParameterTag included an identifier at that position with no '.text'. +////interface /*I*/I {} +//// +/////** +//// * @param /*use*/[|foo|] I pity the foo +//// */ +////function f([|/*def*/{| "isWriteAccess": true, "isDefinition": true |}foo|]: I) { +//// return [|foo|]; +////} + +const ranges = test.ranges(); +goTo.marker("use"); +verify.goToDefinitionIs("def"); +verify.goToType("use", "I"); + +goTo.marker("use"); +verify.quickInfoIs("(parameter) foo: I", "I pity the foo"); + +verify.singleReferenceGroup("(parameter) foo: I"); +verify.rangesAreDocumentHighlights(); +verify.rangesAreRenameLocations(); From 0140e6df77ccf94ac4274dd8a8235fd9c8af7a9d Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 15 May 2017 15:02:47 -0700 Subject: [PATCH 201/282] Remove goToImplementation test, not supported for parameters --- src/services/findAllReferences.ts | 2 +- tests/cases/fourslash/jsDocGoToImplementation.ts | 10 ---------- 2 files changed, 1 insertion(+), 11 deletions(-) delete mode 100644 tests/cases/fourslash/jsDocGoToImplementation.ts diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 16a516c2603..8581dc3989d 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -67,7 +67,7 @@ namespace ts.FindAllReferences { } function getImplementationReferenceEntries(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined { - if (node.parent.kind === SyntaxKind.SourceFile) { + if (node.kind === SyntaxKind.SourceFile) { return undefined; } // If invoked directly on a shorthand property assignment, then return diff --git a/tests/cases/fourslash/jsDocGoToImplementation.ts b/tests/cases/fourslash/jsDocGoToImplementation.ts deleted file mode 100644 index cad5c29c82f..00000000000 --- a/tests/cases/fourslash/jsDocGoToImplementation.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -/////** -//// * @param /**/[|foo|] I pity the foo -//// */ -////function f([|foo|]: number) { -//// return foo; -////} - -verify.allRangesAppearInImplementationList(""); From 4d028a81eeb8909f2be3a89fa14e8291199b656c Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 15 May 2017 15:10:52 -0700 Subject: [PATCH 202/282] getTokenAtPositionWorker: Remove duplicate loop --- src/services/utilities.ts | 48 ++++++++++++--------------------------- 1 file changed, 15 insertions(+), 33 deletions(-) diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 4ae9204f7ed..e452d18de48 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -651,44 +651,26 @@ namespace ts { return current; } - if (includeJsDocComment) { - const jsDocChildren = ts.filter(current.getChildren(), isJSDocNode); - for (const jsDocChild of jsDocChildren) { - const start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - const end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === SyntaxKind.EndOfFileToken)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - const previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - // find the child that contains 'position' for (const child of current.getChildren()) { - // all jsDocComment nodes were already visited - if (isJSDocNode(child)) { + if (isJSDocNode(child) && !includeJsDocComment) { continue; } + const start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - const end = child.getEnd(); - if (position < end || (position === end && child.kind === SyntaxKind.EndOfFileToken)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - const previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + break; + } + + const end = child.getEnd(); + if (position < end || (position === end && child.kind === SyntaxKind.EndOfFileToken)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + const previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } From 93b1eafb9f9d6bd6c82fe99f2ed752d9772285a4 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 15:25:21 -0700 Subject: [PATCH 203/282] Improve arity error messages For calls with one signature. --- src/compiler/checker.ts | 22 +++++++++++++++++++++- src/compiler/diagnosticMessages.json | 8 ++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d6f56a69b9a..5be1fb633cd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15370,7 +15370,27 @@ namespace ts { } } else { - reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + if (signatures.length === 1) { + if (typeArguments && typeArguments.length !== length(signatures[0].typeParameters)) { + const minTypeArgumentCount = getMinTypeArgumentCount(signatures[0].typeParameters); + const paramMessage = length(signatures[0].typeParameters) > minTypeArgumentCount ? + `${minTypeArgumentCount}-${length(signatures[0].typeParameters)}` : + minTypeArgumentCount.toString(); + reportError(Diagnostics.Expected_0_type_arguments_but_got_1, paramMessage, typeArguments.length.toString()); + } + else { + const argMessage = getSpreadArgumentIndex(args) > -1 ? + "a minimum of " + (args.length - 1) : + args.length.toString(); + const paramMessage = signatures[0].hasRestParameter ? "at least " + signatures[0].minArgumentCount : + signatures[0].minArgumentCount < signatures[0].parameters.length ? `${signatures[0].minArgumentCount}-${signatures[0].parameters.length}` : + signatures[0].minArgumentCount.toString(); + reportError(Diagnostics.Expected_0_arguments_but_got_1, paramMessage, argMessage); + } + } + else { + reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + } } // No signature was applicable. We have already reported the errors for the invalid signature. diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4aee7a37a88..849b780380f 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1855,6 +1855,14 @@ "category": "Error", "code": 2552 }, + "Expected {0} arguments, but got {1}.": { + "category": "Error", + "code": 2553 + }, + "Expected {0} type arguments, but got {1}.": { + "category": "Error", + "code": 2554 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 From e5e833e53ed53671d51e77eba2a19b21d7d6b09b Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 15:26:22 -0700 Subject: [PATCH 204/282] Update baselines --- .../reference/ES5SymbolProperty5.errors.txt | 4 +- .../baselines/reference/baseCheck.errors.txt | 4 +- ...dSameNameFunctionDeclarationES5.errors.txt | 4 +- ...dSameNameFunctionDeclarationES6.errors.txt | 4 +- ...ameFunctionDeclarationStrictES5.errors.txt | 16 ++-- ...ameFunctionDeclarationStrictES6.errors.txt | 16 ++-- ...hIncorrectNumberOfTypeArguments.errors.txt | 56 ++++++------- ...enericFunctionWithTypeArguments.errors.txt | 28 +++---- .../reference/callOnInstance.errors.txt | 6 +- ...lWithWrongNumberOfTypeArguments.errors.txt | 8 +- ...ssWithBaseClassButNoConstructor.errors.txt | 16 ++-- .../classWithConstructors.errors.txt | 8 +- ...classWithoutExplicitConstructor.errors.txt | 8 +- .../reference/cloduleTest2.errors.txt | 16 ++-- ...ericRecursiveBaseClassReference.errors.txt | 4 +- ...torInvocationWithTooFewTypeArgs.errors.txt | 4 +- .../couldNotSelectGenericOverload.errors.txt | 8 +- ...ClassWithoutExplicitConstructor.errors.txt | 8 +- ...lassWithoutExplicitConstructor3.errors.txt | 16 ++-- ...llingBaseImplWithOptionalParams.errors.txt | 4 +- .../emptyTypeArgumentList.errors.txt | 4 +- .../emptyTypeArgumentListWithNew.errors.txt | 4 +- ...rdReferenceForwadingConstructor.errors.txt | 4 +- .../reference/functionCall11.errors.txt | 8 +- .../reference/functionCall12.errors.txt | 4 +- .../reference/functionCall13.errors.txt | 4 +- .../reference/functionCall16.errors.txt | 4 +- .../reference/functionCall17.errors.txt | 4 +- .../reference/functionCall6.errors.txt | 8 +- .../reference/functionCall7.errors.txt | 8 +- .../reference/functionCall8.errors.txt | 4 +- .../reference/functionCall9.errors.txt | 4 +- ...functionConstraintSatisfaction2.errors.txt | 8 +- ...kedInsideItsContainingFunction1.errors.txt | 24 +++--- .../genericDefaultsErrors.errors.txt | 8 +- ...unctionsWithOptionalParameters2.errors.txt | 4 +- .../genericWithOpenTypeParameters1.errors.txt | 8 +- .../reference/grammarAmbiguities.errors.txt | 8 +- .../reference/grammarAmbiguities1.errors.txt | 8 +- ...sWithWrongNumberOfTypeArguments.errors.txt | 8 +- ...NonGenericTypeWithTypeArguments.errors.txt | 16 ++-- .../reference/iteratorSpreadInCall.errors.txt | 4 +- .../iteratorSpreadInCall10.errors.txt | 4 +- .../iteratorSpreadInCall2.errors.txt | 4 +- .../iteratorSpreadInCall4.errors.txt | 4 +- ...leFunctionParametersAsOptional2.errors.txt | 12 +-- ...citTypeParameterAndArgumentType.errors.txt | 4 +- .../optionalParamArgsTest.errors.txt | 80 +++++++++---------- ...ResolutionOnDefaultConstructor1.errors.txt | 4 +- ...IOnCallAfterFunctionExpression1.errors.txt | 4 +- .../requiredInitializedParameter1.errors.txt | 8 +- .../restParamsWithNonRestParams.errors.txt | 4 +- ...hIncompleteTemplateExpressions4.errors.txt | 4 +- ...hIncompleteTemplateExpressions5.errors.txt | 4 +- .../thisTypeInFunctionsNegative.errors.txt | 40 +++++----- .../tooManyTypeParameters1.errors.txt | 12 +-- ...OnFunctionsWithNoTypeParameters.errors.txt | 8 +- ...eAssertionToGenericFunctionType.errors.txt | 4 +- .../reference/typeAssertions.errors.txt | 4 +- .../typesWithPublicConstructor.errors.txt | 4 +- .../unionTypeCallSignatures.errors.txt | 64 +++++++-------- .../unionTypeCallSignatures4.errors.txt | 16 ++-- .../unionTypeConstructSignatures.errors.txt | 60 +++++++------- ...unctionCallsWithTypeParameters1.errors.txt | 16 ++-- 64 files changed, 379 insertions(+), 379 deletions(-) diff --git a/tests/baselines/reference/ES5SymbolProperty5.errors.txt b/tests/baselines/reference/ES5SymbolProperty5.errors.txt index bbfb64b6459..278374e417d 100644 --- a/tests/baselines/reference/ES5SymbolProperty5.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2553: Expected 0 arguments, but got 1. ==== tests/cases/conformance/Symbols/ES5SymbolProperty5.ts (1 errors) ==== @@ -10,4 +10,4 @@ tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2346: Suppli (new C)[Symbol.iterator](0) // Should error ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/baseCheck.errors.txt b/tests/baselines/reference/baseCheck.errors.txt index 1353d6e1a08..cf1da0a5358 100644 --- a/tests/baselines/reference/baseCheck.errors.txt +++ b/tests/baselines/reference/baseCheck.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/baseCheck.ts(9,18): error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'? -tests/cases/compiler/baseCheck.ts(17,53): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/baseCheck.ts(17,53): error TS2553: Expected 2 arguments, but got 1. tests/cases/compiler/baseCheck.ts(17,59): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/baseCheck.ts(18,62): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/baseCheck.ts(19,59): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. @@ -30,7 +30,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'. class D extends C { constructor(public z: number) { super(this.z) } } // too few params ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. ~~~~ !!! error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. class E extends C { constructor(public z: number) { super(0, this.z) } } diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt index 3efa85d1cc7..1ed2175833a 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt @@ -3,7 +3,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(5,9): error TS tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(8,18): error TS2393: Duplicate function implementation. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(12,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts (6 errors) ==== @@ -34,4 +34,4 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt index 5d15278f098..0669f2bdebc 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt @@ -3,7 +3,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(5,9): error TS tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(8,18): error TS2393: Duplicate function implementation. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(12,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts (6 errors) ==== @@ -34,4 +34,4 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt index 36ce2d8c488..0647034272d 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(4,18): error TS1250: Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(6,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(6,9): error TS2553: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(9,18): error TS1250: Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(14,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(11,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(14,5): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts (6 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } else { function foo() { } // Error to declare function in block scope @@ -25,14 +25,14 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt index 7b8834c5594..32da909c2fe 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(6,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(14,5): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(6,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(11,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(14,5): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts (4 errors) ==== @@ -12,21 +12,21 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } else { function foo() { } foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } foo(10); foo(); // not ok ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt index 0e8e8ff9303..3c5b03fab50 100644 --- a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt @@ -1,17 +1,17 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2554: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2554: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2554: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2554: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2554: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2554: Expected 0 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2554: Expected 0 type arguments, but got 3. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts (14 errors) ==== @@ -21,26 +21,26 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti function f(x: T, y: U): T { return null; } var r1 = f(1, ''); ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. var r1b = f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 3. var f2 = (x: T, y: U): T => { return null; } var r2 = f2(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. var r2b = f2(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 3. var f3: { (x: T, y: U): T; } var r3 = f3(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. var r3b = f3(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 3. class C { f(x: T, y: U): T { @@ -49,10 +49,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r4 = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. var r4b = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 3. interface I { f(x: T, y: U): T; @@ -60,10 +60,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i: I; var r5 = i.f(1, ''); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. var r5b = i.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 3. class C2 { f(x: T, y: U): T { @@ -72,10 +72,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r6 = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r6b = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 3. interface I2 { f(x: T, y: U): T; @@ -83,7 +83,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i2: I2; var r7 = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r7b = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 0 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt index 6a11751ead3..466c6e0828e 100644 --- a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt +++ b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2554: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(40,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(43,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,17 +16,17 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun function f(x: number) { return null; } var r = f(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var f2 = (x: number) => { return null; } var r2 = f2(1); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var f3: { (x: number): any; } var r3 = f3(1); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. class C { f(x: number) { @@ -35,7 +35,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r4 = (new C()).f(1); ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. interface I { f(x: number): any; @@ -43,7 +43,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i: I; var r5 = i.f(1); ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. class C2 { f(x: number) { @@ -52,7 +52,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r6 = (new C2()).f(1); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. interface I2 { f(x: number); @@ -60,7 +60,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i2: I2; var r7 = i2.f(1); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var a; var r8 = a(); diff --git a/tests/baselines/reference/callOnInstance.errors.txt b/tests/baselines/reference/callOnInstance.errors.txt index 4f80088ab75..742303d5cf0 100644 --- a/tests/baselines/reference/callOnInstance.errors.txt +++ b/tests/baselines/reference/callOnInstance.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/callOnInstance.ts(1,18): error TS2300: Duplicate identifier 'D'. tests/cases/compiler/callOnInstance.ts(3,15): error TS2300: Duplicate identifier 'D'. -tests/cases/compiler/callOnInstance.ts(7,19): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/callOnInstance.ts(7,19): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/compiler/callOnInstance.ts(7,19): error TS2553: Expected 0 arguments, but got 1. tests/cases/compiler/callOnInstance.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'C' has no compatible call signatures. @@ -18,9 +18,9 @@ tests/cases/compiler/callOnInstance.ts(10,1): error TS2349: Cannot invoke an exp var s2: string = (new D(1))(); ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. - ~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. + ~~~~~~~~ +!!! error TS2553: Expected 0 arguments, but got 1. declare class C { constructor(value: number); } (new C(1))(); // Error for calling an instance diff --git a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt index a3776946292..be5d2ed364f 100644 --- a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2554: Expected 2 type arguments, but got 3. ==== tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -7,8 +7,8 @@ tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2346: S f(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. f(); f(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt index 75f24d8c45a..197e38bdae1 100644 --- a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt +++ b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(22,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(31,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(39,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(10,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(22,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(31,10): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(39,10): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts (4 errors) ==== @@ -16,7 +16,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r = C; var c = new C(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var c2 = new C(1); // ok class Base2 { @@ -30,7 +30,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r2 = D; var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var d2 = new D(1); // ok // specialized base class @@ -41,7 +41,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r3 = D2; var d3 = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var d4 = new D(1); // ok class D3 extends Base2 { @@ -51,5 +51,5 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r4 = D3; var d5 = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var d6 = new D(1); // ok \ No newline at end of file diff --git a/tests/baselines/reference/classWithConstructors.errors.txt b/tests/baselines/reference/classWithConstructors.errors.txt index 61e0b1248b1..a983ff104d3 100644 --- a/tests/baselines/reference/classWithConstructors.errors.txt +++ b/tests/baselines/reference/classWithConstructors.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(6,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(6,13): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(15,14): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(21,13): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(31,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(31,13): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(40,14): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(46,13): error TS2346: Supplied parameters do not match any signature of call target. @@ -14,7 +14,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var c2 = new C(''); // ok class C2 { @@ -45,7 +45,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var c2 = new C(''); // ok class C2 { diff --git a/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt b/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt index 981f38f017c..8fd3a8412c0 100644 --- a/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt +++ b/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(7,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(15,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(7,10): error TS2553: Expected 0 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(15,10): error TS2553: Expected 0 arguments, but got 1. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts (2 errors) ==== @@ -11,7 +11,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/cl var c = new C(); var c2 = new C(null); // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. class D { x = 2 @@ -21,4 +21,4 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/cl var d = new D(); var d2 = new D(null); // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/cloduleTest2.errors.txt b/tests/baselines/reference/cloduleTest2.errors.txt index 9659b5b0d4c..f8eb1547679 100644 --- a/tests/baselines/reference/cloduleTest2.errors.txt +++ b/tests/baselines/reference/cloduleTest2.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/cloduleTest2.ts(4,13): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/cloduleTest2.ts(10,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/cloduleTest2.ts(4,13): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(10,13): error TS2553: Expected 1 arguments, but got 0. tests/cases/compiler/cloduleTest2.ts(18,7): error TS2339: Property 'bar' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(19,7): error TS2339: Property 'y' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(27,7): error TS2339: Property 'bar' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(28,7): error TS2339: Property 'y' does not exist on type 'm3d'. -tests/cases/compiler/cloduleTest2.ts(33,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/cloduleTest2.ts(33,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(36,10): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/cloduleTest2.ts (8 errors) ==== @@ -14,7 +14,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters d declare class m3d { constructor(foo); foo(): void ; static bar(); } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. } module T2 { @@ -22,7 +22,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters d module m3d { export var y = 2; } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. } module T3 { @@ -55,9 +55,9 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2346: Supplied parameters d declare class m3d { constructor(foo); foo(): void; static bar(); } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. declare class m4d extends m3d { } var r2 = new m4d(); // error ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt index a70eb0e5e2c..9de8fb36b26 100644 --- a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt +++ b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(1,7): error TS2506: 'S18' is referenced directly or indirectly in its own base expression. -tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): error TS2553: Expected 0 arguments, but got 1. ==== tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts (2 errors) ==== @@ -10,5 +10,5 @@ tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): erro } (new S18(123)).S18 = 0; ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt index 8a15123dfc8..8fec159562c 100644 --- a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt +++ b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2554: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts (1 errors) ==== @@ -12,5 +12,5 @@ tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS23 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt b/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt index bafa2bc4237..429d27fd004 100644 --- a/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt +++ b/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/couldNotSelectGenericOverload.ts(3,11): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/couldNotSelectGenericOverload.ts(3,11): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2553: Expected 1 arguments, but got 2. ==== tests/cases/compiler/couldNotSelectGenericOverload.ts (2 errors) ==== @@ -7,11 +7,11 @@ tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2346: Suppl var b = [1, ""]; var b1G = makeArray(1, ""); // any, no error ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. var b2G = makeArray(b); // any[] function makeArray2(items: any[]): any[] { return items; } var b3G = makeArray2(1, ""); // error ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt index 75720d86404..1fcf6e565ca 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(24,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(11,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(24,9): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts (2 errors) ==== @@ -15,7 +15,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var r2 = new Derived(1); class Base2 { @@ -30,5 +30,5 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var d2 = new D(new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt index 6b9619cdac6..e447540f853 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(21,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(22,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(44,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(45,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(21,9): error TS2553: Expected 2 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(22,10): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(44,9): error TS2553: Expected 2 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(45,10): error TS2553: Expected 2 arguments, but got 1. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts (4 errors) ==== @@ -27,10 +27,10 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 0. var r2 = new Derived2(1); // error ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. var r3 = new Derived('', ''); class Base2 { @@ -54,8 +54,8 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D2(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 0. var d2 = new D2(new Date()); // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. var d3 = new D2(new Date(), new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt index 3410867f818..de1fa1b36c7 100644 --- a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt +++ b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts (1 errors) ==== @@ -16,4 +16,4 @@ tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): erro var y: MyClass = new MyClass(); y.myMethod(); // error ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTypeArgumentList.errors.txt b/tests/baselines/reference/emptyTypeArgumentList.errors.txt index 9f252b127a1..eea58f5a4d7 100644 --- a/tests/baselines/reference/emptyTypeArgumentList.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentList.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2554: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument function foo() { } foo<>(); ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt index 799e35d0d47..c60e4221997 100644 --- a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2554: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type ar class foo { } new foo<>(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt index f0976ba7398..acfa0d0b028 100644 --- a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt +++ b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts (1 errors) ==== @@ -7,7 +7,7 @@ tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error T function f() { var d1 = new derived(); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var d2 = new derived(4); } diff --git a/tests/baselines/reference/functionCall11.errors.txt b/tests/baselines/reference/functionCall11.errors.txt index f1a5949acd7..4425bc6fbfa 100644 --- a/tests/baselines/reference/functionCall11.errors.txt +++ b/tests/baselines/reference/functionCall11.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/functionCall11.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall11.ts(4,1): error TS2553: Expected 1-2 arguments, but got 0. tests/cases/compiler/functionCall11.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall11.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall11.ts(6,1): error TS2553: Expected 1-2 arguments, but got 3. ==== tests/cases/compiler/functionCall11.ts (3 errors) ==== @@ -9,11 +9,11 @@ tests/cases/compiler/functionCall11.ts(6,1): error TS2346: Supplied parameters d foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. foo('foo', 1, 'bar'); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall12.errors.txt b/tests/baselines/reference/functionCall12.errors.txt index ef93a34b080..09adbf933dc 100644 --- a/tests/baselines/reference/functionCall12.errors.txt +++ b/tests/baselines/reference/functionCall12.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall12.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall12.ts(4,1): error TS2553: Expected 1-3 arguments, but got 0. tests/cases/compiler/functionCall12.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. @@ -9,7 +9,7 @@ tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type '3' foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall13.errors.txt b/tests/baselines/reference/functionCall13.errors.txt index a89d7fc1efa..3e5ed7655b8 100644 --- a/tests/baselines/reference/functionCall13.errors.txt +++ b/tests/baselines/reference/functionCall13.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall13.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall13.ts(4,1): error TS2553: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -8,7 +8,7 @@ tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall16.errors.txt b/tests/baselines/reference/functionCall16.errors.txt index d338c1305dd..04b463031f2 100644 --- a/tests/baselines/reference/functionCall16.errors.txt +++ b/tests/baselines/reference/functionCall16.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall16.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall16.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall16.ts(5,1): error TS2553: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' foo('foo', 'bar'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall17.errors.txt b/tests/baselines/reference/functionCall17.errors.txt index f266554b518..8d1ba39e2b4 100644 --- a/tests/baselines/reference/functionCall17.errors.txt +++ b/tests/baselines/reference/functionCall17.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall17.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall17.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall17.ts(4,1): error TS2553: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall17.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall6.errors.txt b/tests/baselines/reference/functionCall6.errors.txt index 3d590d8f5c2..baaca457054 100644 --- a/tests/baselines/reference/functionCall6.errors.txt +++ b/tests/baselines/reference/functionCall6.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/functionCall6.ts(3,5): error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall6.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/functionCall6.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall6.ts(4,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/functionCall6.ts(5,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionCall6.ts (3 errors) ==== @@ -11,8 +11,8 @@ tests/cases/compiler/functionCall6.ts(5,1): error TS2346: Supplied parameters do !!! error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. foo('foo', 'bar'); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall7.errors.txt b/tests/baselines/reference/functionCall7.errors.txt index 138c5f62f16..aaa59ab5e1f 100644 --- a/tests/baselines/reference/functionCall7.errors.txt +++ b/tests/baselines/reference/functionCall7.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/functionCall7.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall7.ts(5,1): error TS2553: Expected 1 arguments, but got 2. tests/cases/compiler/functionCall7.ts(6,5): error TS2345: Argument of type '4' is not assignable to parameter of type 'c1'. -tests/cases/compiler/functionCall7.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall7.ts(7,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionCall7.ts (3 errors) ==== @@ -10,11 +10,11 @@ tests/cases/compiler/functionCall7.ts(7,1): error TS2346: Supplied parameters do foo(myC); foo(myC, myC); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. foo(4); ~ !!! error TS2345: Argument of type '4' is not assignable to parameter of type 'c1'. foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall8.errors.txt b/tests/baselines/reference/functionCall8.errors.txt index 7cf197d5812..cdb2ebc44cf 100644 --- a/tests/baselines/reference/functionCall8.errors.txt +++ b/tests/baselines/reference/functionCall8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall8.ts(3,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall8.ts(3,1): error TS2553: Expected 0-1 arguments, but got 2. tests/cases/compiler/functionCall8.ts(4,5): error TS2345: Argument of type '4' is not assignable to parameter of type 'string'. @@ -7,7 +7,7 @@ tests/cases/compiler/functionCall8.ts(4,5): error TS2345: Argument of type '4' i foo('foo'); foo('foo', 'bar'); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-1 arguments, but got 2. foo(4); ~ !!! error TS2345: Argument of type '4' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall9.errors.txt b/tests/baselines/reference/functionCall9.errors.txt index 83cda64e204..aebd6cc5235 100644 --- a/tests/baselines/reference/functionCall9.errors.txt +++ b/tests/baselines/reference/functionCall9.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall9.ts(4,11): error TS2345: Argument of type '"bar"' is not assignable to parameter of type 'number'. -tests/cases/compiler/functionCall9.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionCall9.ts(5,1): error TS2553: Expected 0-2 arguments, but got 3. ==== tests/cases/compiler/functionCall9.ts (2 errors) ==== @@ -11,5 +11,5 @@ tests/cases/compiler/functionCall9.ts(5,1): error TS2346: Supplied parameters do !!! error TS2345: Argument of type '"bar"' is not assignable to parameter of type 'number'. foo('foo', 1, 'bar'); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-2 arguments, but got 3. foo(); \ No newline at end of file diff --git a/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt b/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt index 06cdca868ad..e770eb5932b 100644 --- a/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt +++ b/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'Function'. -tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(6,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(7,1): error TS2553: Expected 1 arguments, but got 2. tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(23,14): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(x: string) => string'. Type 'Function' provides no match for the signature '(x: string): string'. tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(24,15): error TS2345: Argument of type '(x: string[]) => string[]' is not assignable to parameter of type '(x: string) => string'. @@ -36,10 +36,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstrain !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'Function'. foo(() => { }, 1); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. foo(1, () => { }); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. function foo2 string>(x: T): T { return x; } diff --git a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt index aec6b9c34b7..7092e8ef0ae 100644 --- a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt +++ b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt @@ -1,33 +1,33 @@ -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2554: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(3,16): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2554: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(12,17): error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2554: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts (8 errors) ==== function foo(x:T, y:U, f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r4 = f(null); var r11 = f(x); var r21 = f(x); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r31 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r41 = f(null); var r12 = f(y); @@ -35,9 +35,9 @@ tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15 !!! error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. var r22 = f(y); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r32 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r42 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/genericDefaultsErrors.errors.txt b/tests/baselines/reference/genericDefaultsErrors.errors.txt index 3d792f022ac..8ac07d68e95 100644 --- a/tests/baselines/reference/genericDefaultsErrors.errors.txt +++ b/tests/baselines/reference/genericDefaultsErrors.errors.txt @@ -3,8 +3,8 @@ tests/cases/compiler/genericDefaultsErrors.ts(4,59): error TS2344: Type 'T' does Type 'string' is not assignable to type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(5,44): error TS2344: Type 'T' does not satisfy the constraint 'number'. tests/cases/compiler/genericDefaultsErrors.ts(6,39): error TS2344: Type 'number' does not satisfy the constraint 'T'. -tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2554: Expected 2-3 type arguments, but got 1. +tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2554: Expected 2-3 type arguments, but got 4. tests/cases/compiler/genericDefaultsErrors.ts(17,13): error TS2345: Argument of type '"a"' is not assignable to parameter of type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(19,11): error TS2428: All declarations of 'i00' must have identical type parameters. tests/cases/compiler/genericDefaultsErrors.ts(20,11): error TS2428: All declarations of 'i00' must have identical type parameters. @@ -44,12 +44,12 @@ tests/cases/compiler/genericDefaultsErrors.ts(38,20): error TS4033: Property 'x' f11(); // ok f11<1>(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2-3 type arguments, but got 1. f11<1, 2>(); // ok f11<1, 2, 3>(); // ok f11<1, 2, 3, 4>(); // error ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2-3 type arguments, but got 4. declare function f12(a?: U): void; f12(); // ok diff --git a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt index 5b9ed348583..02946e0d0bd 100644 --- a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt +++ b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS2553: Expected 1-3 arguments, but got 0. ==== tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts (1 errors) ==== @@ -10,7 +10,7 @@ tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS23 utils.fold(); // error ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 0. utils.fold(null); // no error utils.fold(null, null); // no error utils.fold(null, null, null); // error: Unable to invoke type with no call signatures diff --git a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt index ba9ec881f99..a63ef43848c 100644 --- a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt +++ b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(7,40): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2554: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericWithOpenTypeParameters1.ts (3 errors) ==== @@ -15,9 +15,9 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2346: Supp !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var f2 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var f3 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var f4 = (x: B) => { return x.foo(1); } // no error \ No newline at end of file diff --git a/tests/baselines/reference/grammarAmbiguities.errors.txt b/tests/baselines/reference/grammarAmbiguities.errors.txt index 3d21f10de7b..17861e6fc95 100644 --- a/tests/baselines/reference/grammarAmbiguities.errors.txt +++ b/tests/baselines/reference/grammarAmbiguities.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(8,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(8,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): error TS2553: Expected 1 arguments, but got 2. ==== tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts (2 errors) ==== @@ -12,9 +12,9 @@ tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): er f(g(7)); f(g < A, B > 7); // Should error ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. f(g < A, B > +(7)); // Should error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. \ No newline at end of file diff --git a/tests/baselines/reference/grammarAmbiguities1.errors.txt b/tests/baselines/reference/grammarAmbiguities1.errors.txt index 12df5f3c1e0..1d206b4209d 100644 --- a/tests/baselines/reference/grammarAmbiguities1.errors.txt +++ b/tests/baselines/reference/grammarAmbiguities1.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/grammarAmbiguities1.ts(8,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/grammarAmbiguities1.ts(8,1): error TS2553: Expected 1 arguments, but got 2. tests/cases/compiler/grammarAmbiguities1.ts(8,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. tests/cases/compiler/grammarAmbiguities1.ts(8,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. -tests/cases/compiler/grammarAmbiguities1.ts(9,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/grammarAmbiguities1.ts(9,1): error TS2553: Expected 1 arguments, but got 2. tests/cases/compiler/grammarAmbiguities1.ts(9,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. @@ -16,14 +16,14 @@ tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' ca f(g(7)); f(g < A, B > 7); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. ~~~~~ !!! error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. ~~~~~ !!! error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. f(g < A, B > +(7)); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. ~~~~~ !!! error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. ~~~~~~~~ diff --git a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt index 5162cd28fd5..9c5d62d2419 100644 --- a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2554: Expected 1 type arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2554: Expected 2 type arguments, but got 1. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -12,7 +12,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri var c = new C(); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 type arguments, but got 2. class D { x: T @@ -22,4 +22,4 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri // BUG 794238 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2554: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt index 8322fd3b2e4..4d726c4c8ca 100644 --- a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2554: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2554: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2554: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(18,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,21 +16,21 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGen var c = new C(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. function Foo(): void { } var r = new Foo(); ~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. - ~~~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. + ~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 0 type arguments, but got 1. var f: { (): void }; var r2 = new f(); ~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. - ~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. + ~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 0 type arguments, but got 1. var a: any; // BUG 790977 diff --git a/tests/baselines/reference/iteratorSpreadInCall.errors.txt b/tests/baselines/reference/iteratorSpreadInCall.errors.txt index d26f9ab6447..7e5576baa3a 100644 --- a/tests/baselines/reference/iteratorSpreadInCall.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2553: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2346: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt index bf478012c5d..d302644762a 100644 --- a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2553: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2346 foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt index abf8fc71ed7..3647aa0fd77 100644 --- a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2553: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2346: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt index 3beaf2ce65c..9d444d2269a 100644 --- a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2553: Expected at least 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2346: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected at least 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt index 236827b97bc..30b10dc4ef2 100644 --- a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt +++ b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/bar.ts(1,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/bar.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/bar.ts(3,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/bar.ts(1,1): error TS2553: Expected 3 arguments, but got 0. +tests/cases/compiler/bar.ts(2,1): error TS2553: Expected 3 arguments, but got 1. +tests/cases/compiler/bar.ts(3,1): error TS2553: Expected 3 arguments, but got 2. ==== tests/cases/compiler/foo.js (0 errors) ==== @@ -15,13 +15,13 @@ tests/cases/compiler/bar.ts(3,1): error TS2346: Supplied parameters do not match ==== tests/cases/compiler/bar.ts (3 errors) ==== f(); // Error ~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 3 arguments, but got 0. f(1); // Error ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 3 arguments, but got 1. f(1, 2); // Error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 3 arguments, but got 2. f(1, 2, 3); // OK \ No newline at end of file diff --git a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt index 2fb7bd1bfbb..9107b2b162b 100644 --- a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt +++ b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(10,30): error TS2345: Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2554: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts (2 errors) ==== @@ -21,5 +21,5 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): e !!! error TS2345: Type 'string' is not assignable to type 'number'. var r7b = map([1, ""], (x) => x.toString()); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 2 type arguments, but got 1. var r8 = map([1, ""], (x) => x.toString()); \ No newline at end of file diff --git a/tests/baselines/reference/optionalParamArgsTest.errors.txt b/tests/baselines/reference/optionalParamArgsTest.errors.txt index 05fefa85065..d16009c2b9d 100644 --- a/tests/baselines/reference/optionalParamArgsTest.errors.txt +++ b/tests/baselines/reference/optionalParamArgsTest.errors.txt @@ -1,25 +1,25 @@ tests/cases/compiler/optionalParamArgsTest.ts(31,12): error TS2393: Duplicate function implementation. tests/cases/compiler/optionalParamArgsTest.ts(34,12): error TS2393: Duplicate function implementation. -tests/cases/compiler/optionalParamArgsTest.ts(98,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(99,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(100,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(101,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(102,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(103,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(104,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(105,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(106,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(107,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(108,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(109,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(110,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(111,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(112,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(113,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(114,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(115,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(116,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/optionalParamArgsTest.ts(98,1): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(99,1): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(100,1): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(101,1): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(102,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(103,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(104,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(105,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(106,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(107,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(108,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(109,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(110,1): error TS2553: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(111,1): error TS2553: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(112,1): error TS2553: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(113,1): error TS2553: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(114,1): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(115,1): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(116,1): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2553: Expected 1-2 arguments, but got 0. ==== tests/cases/compiler/optionalParamArgsTest.ts (22 errors) ==== @@ -126,64 +126,64 @@ tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2346: Supplied par // Negative tests - we expect these cases to fail c1o1.C1M1(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. i1o1.C1M1(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. F1(1); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. L1(1); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. c1o1.C1M2(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. i1o1.C1M2(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. F2(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. L2(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. c1o1.C1M2(1,2); ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. i1o1.C1M2(1,2); ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. F2(1,2); ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. L2(1,2); ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. c1o1.C1M3(1,2,3); ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-2 arguments, but got 3. i1o1.C1M3(1,2,3); ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-2 arguments, but got 3. F3(1,2,3); ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-2 arguments, but got 3. L3(1,2,3); ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-2 arguments, but got 3. c1o1.C1M4(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. i1o1.C1M4(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. F4(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. L4(); ~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. function fnOpt1(id: number, children: number[] = [], expectedPath: number[] = [], isRoot?: boolean): void {} function fnOpt2(id: number, children?: number[], expectedPath?: number[], isRoot?: boolean): void {} diff --git a/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt b/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt index 1922df6852a..c106c3b64ac 100644 --- a/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt +++ b/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2553: Expected 0 arguments, but got 1. ==== tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts (1 errors) ==== @@ -6,6 +6,6 @@ tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2 public clone() { return new Bar(0); ~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } } \ No newline at end of file diff --git a/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt b/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt index 7fc9396ac28..e03ef38b1ac 100644 --- a/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt +++ b/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(1,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(1,9): error TS2553: Expected 0 arguments, but got 1. tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(2,7): error TS2304: Cannot find name 'window'. @@ -7,7 +7,7 @@ tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpress ~~~~~~~~~~~~~~~ (window).foo; ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. ~~~~~~ !!! error TS2304: Cannot find name 'window'. \ No newline at end of file diff --git a/tests/baselines/reference/requiredInitializedParameter1.errors.txt b/tests/baselines/reference/requiredInitializedParameter1.errors.txt index ef958dbdec9..d227eb1fc6e 100644 --- a/tests/baselines/reference/requiredInitializedParameter1.errors.txt +++ b/tests/baselines/reference/requiredInitializedParameter1.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/requiredInitializedParameter1.ts(11,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/requiredInitializedParameter1.ts(11,1): error TS2553: Expected 3 arguments, but got 2. +tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2553: Expected 3 arguments, but got 1. ==== tests/cases/compiler/requiredInitializedParameter1.ts (2 errors) ==== @@ -15,14 +15,14 @@ tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2346: Suppl f1(0, 1); ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 3 arguments, but got 2. f2(0, 1); f3(0, 1); f4(0, 1); f1(0); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 3 arguments, but got 1. f2(0); f3(0); f4(0); \ No newline at end of file diff --git a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt index 4fdb98206c7..5f22e34383a 100644 --- a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt +++ b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2553: Expected at least 1 arguments, but got 0. ==== tests/cases/compiler/restParamsWithNonRestParams.ts (1 errors) ==== @@ -7,6 +7,6 @@ tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2346: Supplied function foo2(a:string, ...b:number[]){} foo2(); // should be an error ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected at least 1 arguments, but got 0. function foo3(a?:string, ...b:number[]){} foo3(); // error but shouldn't be \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt index cc499cb2578..72484f20964 100644 --- a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt +++ b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,1): error TS2553: Expected 3 arguments, but got 4. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,24): error TS1109: Expression expected. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,28): error TS1109: Expression expected. @@ -10,7 +10,7 @@ tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,28): // Incomplete call, but too many parameters. f `123qdawdrqw${ 1 }${ }${ ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 3 arguments, but got 4. ~ !!! error TS1109: Expression expected. diff --git a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt index 0a4f0724cc2..8d944e5b1fd 100644 --- a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt +++ b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,1): error TS2553: Expected 3 arguments, but got 4. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,30): error TS1109: Expression expected. @@ -9,6 +9,6 @@ tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,30): // Incomplete call, but too many parameters. f `123qdawdrqw${ 1 }${ 2 }${ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 3 arguments, but got 4. !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt index a3771839dc5..c9e7dfcc490 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt @@ -10,26 +10,26 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(62,97): er Object literal may only specify known properties, and 'explicitStructural' does not exist in type '{ y: string; f: (this: { y: number; }, x: number) => number; }'. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(63,110): error TS2322: Type '{ wrongName: number; explicitStructural: (this: { y: number; }, x: number) => number; }' is not assignable to type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. Object literal may only specify known properties, and 'explicitStructural' does not exist in type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(65,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(65,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(66,6): error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(67,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(67,1): error TS2553: Expected 1 arguments, but got 2. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(68,1): error TS2684: The 'this' context of type '{ y: string; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. Types of property 'y' are incompatible. Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(69,1): error TS2684: The 'this' context of type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. Property 'y' is missing in type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(72,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(72,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(73,13): error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(74,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(75,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(74,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(75,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(76,16): error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(77,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(78,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(77,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(78,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(79,16): error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(80,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(81,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(80,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(81,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(82,20): error TS2345: Argument of type '"wrong type 3"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(83,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(83,1): error TS2553: Expected 1 arguments, but got 2. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(86,5): error TS2322: Type '(this: { y: number; }, x: number) => number' is not assignable to type '(this: void, x: number) => number'. The 'this' types of each signature are incompatible. Type 'void' is not assignable to type '{ y: number; }'. @@ -187,13 +187,13 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e ok.f(); // not enough arguments ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. ok.f('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. ok.f(13, 'too many arguments'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. wrongPropertyType.f(13); ~~~~~~~~~~~~~~~~~ !!! error TS2684: The 'this' context of type '{ y: string; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. @@ -207,40 +207,40 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e let c = new C(); c.explicitC(); // not enough arguments ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. c.explicitC('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. c.explicitC(13, 'too many arguments'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. c.explicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. c.explicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. c.explicitThis(14, 'too many arguments 2'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. c.implicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. c.implicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. c.implicitThis(14, 'too many arguments 2'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. c.explicitProperty(); // not enough arguments ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. c.explicitProperty('wrong type 3'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 3"' is not assignable to parameter of type 'number'. c.explicitProperty(15, 'too many arguments 3'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. // oops, this triggers contextual typing, which needs to be updated to understand that =>'s `this` is void. let specifiedToVoid: (this: void, x: number) => number = explicitStructural; diff --git a/tests/baselines/reference/tooManyTypeParameters1.errors.txt b/tests/baselines/reference/tooManyTypeParameters1.errors.txt index 2355ef55e56..8ff1f031d9b 100644 --- a/tests/baselines/reference/tooManyTypeParameters1.errors.txt +++ b/tests/baselines/reference/tooManyTypeParameters1.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2554: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2554: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2554: Expected 1 type arguments, but got 2. tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type 'I' requires 1 type argument(s). @@ -8,17 +8,17 @@ tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type function f() { } f(); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 type arguments, but got 2. var x = () => {}; x(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 type arguments, but got 2. class C {} var c = new C(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1 type arguments, but got 2. interface I {} var i: I; diff --git a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt index b2d9e3f8aaf..df122c8d591 100644 --- a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt +++ b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt @@ -1,19 +1,19 @@ -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2554: Expected 0 type arguments, but got 1. tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(3,15): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2554: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts (3 errors) ==== function foo(f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var r4 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt index 7d99934f5ea..be41618433a 100644 --- a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt +++ b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(5,13): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/typeAssertionToGenericFunctionType.ts (2 errors) ==== @@ -12,4 +12,4 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2346: S !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. x.b(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index cdd576e6d8b..28b72d37767 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2554: Expected 0 type arguments, but got 1. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(31,12): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeBase'. Property 'p' is missing in type 'SomeOther'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(35,15): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeDerived'. @@ -30,7 +30,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err fn1(fn2(4)); // Error ~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var a: any; var s: string; diff --git a/tests/baselines/reference/typesWithPublicConstructor.errors.txt b/tests/baselines/reference/typesWithPublicConstructor.errors.txt index 17abc57f6df..e46fe7e0ddd 100644 --- a/tests/baselines/reference/typesWithPublicConstructor.errors.txt +++ b/tests/baselines/reference/typesWithPublicConstructor.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(8,5): error TS2322: Type 'Function' is not assignable to type '() => void'. Type 'Function' provides no match for the signature '(): void'. -tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/conformance/types/members/typesWithPublicConstructor.ts (2 errors) ==== @@ -23,5 +23,5 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): erro var c2 = new C2(); ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var r2: (x: number) => void = c2.constructor; \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures.errors.txt b/tests/baselines/reference/unionTypeCallSignatures.errors.txt index 0398c0cec47..0172de7b351 100644 --- a/tests/baselines/reference/unionTypeCallSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures.errors.txt @@ -5,30 +5,30 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(16,1): error TS23 tests/cases/conformance/types/union/unionTypeCallSignatures.ts(19,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(20,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(21,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(24,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(24,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(26,36): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(29,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(30,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(31,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(36,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(37,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(40,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(37,12): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(40,12): error TS2553: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(42,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(43,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(47,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(48,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(49,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(43,12): error TS2553: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(47,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(48,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(49,12): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(55,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(59,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(61,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(59,12): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(61,12): error TS2553: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(62,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(63,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(67,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(68,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(69,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(70,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(63,12): error TS2553: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(67,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(68,12): error TS2553: Expected 1 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(69,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(70,12): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2553: Expected 2 arguments, but got 1. ==== tests/cases/conformance/types/union/unionTypeCallSignatures.ts (31 errors) ==== @@ -71,7 +71,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 var unionOfDifferentNumberOfSignatures: { (a: number): number; } | { (a: number): Date; (a: string): boolean; }; unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. unionOfDifferentNumberOfSignatures(10); // error - no call signatures unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -96,31 +96,31 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. var unionWithOptionalParameter2: { (a: string, b?: number): string; } | { (a: string, b: number): number }; strOrNum = unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. strOrNum = unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 0. var unionWithOptionalParameter3: { (a: string, b?: number): string; } | { (a: string): number; }; strOrNum = unionWithOptionalParameter3('hello'); strOrNum = unionWithOptionalParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = unionWithOptionalParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var unionWithRestParameter1: { (a: string, ...b: number[]): string; } | { (a: string, ...b: number[]): number }; strOrNum = unionWithRestParameter1('hello'); @@ -131,41 +131,41 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { (a: string, ...b: number[]): string; } | { (a: string, b: number): number }; strOrNum = unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. strOrNum = unionWithRestParameter2('hello', 10); // error no call signature strOrNum = unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 3. strOrNum = unionWithRestParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 0. var unionWithRestParameter3: { (a: string, ...b: number[]): string; } | { (a: string): number }; strOrNum = unionWithRestParameter3('hello'); strOrNum = unionWithRestParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = unionWithRestParameter3('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 3. strOrNum = unionWithRestParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var unionWithRestParameter4: { (...a: string[]): string; } | { (a: string, b: string): number; }; strOrNum = unionWithRestParameter4("hello"); // error supplied parameters do not match any call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. strOrNum = unionWithRestParameter4("hello", "world"); \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt index 585906a6b5a..f3c489807a6 100644 --- a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(10,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(20,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(23,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(10,1): error TS2553: Expected 1-2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(20,1): error TS2553: Expected 1-2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(23,1): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2553: Expected 2 arguments, but got 3. ==== tests/cases/conformance/types/union/unionTypeCallSignatures4.ts (4 errors) ==== @@ -16,7 +16,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f12("a", "b"); f12("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 3. var f34: F3 | F4; f34("a"); @@ -28,14 +28,14 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f1234("a", "b"); f1234("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 3. var f12345: F1 | F2 | F3 | F4 | F5; f12345("a"); // error ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. f12345("a", "b"); f12345("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt index 813f7701ea8..a84fe952e67 100644 --- a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt @@ -5,29 +5,29 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(16,1): error tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(19,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(20,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(21,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(24,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(24,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(26,40): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(29,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(30,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(31,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(36,53): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(37,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(40,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(37,12): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(40,12): error TS2553: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(42,53): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(43,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(47,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(48,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(49,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(43,12): error TS2553: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(47,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(48,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(49,12): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(55,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(59,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(61,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(59,12): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(61,12): error TS2553: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(62,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(63,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(67,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(68,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(69,12): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(63,12): error TS2553: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(67,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(68,12): error TS2553: Expected 1 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(69,12): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/conformance/types/union/unionTypeConstructSignatures.ts (30 errors) ==== @@ -70,7 +70,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro var unionOfDifferentNumberOfSignatures: { new (a: number): number; } | { new (a: number): Date; new (a: string): boolean; }; new unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. new unionOfDifferentNumberOfSignatures(10); // error - no call signatures new unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -95,31 +95,31 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. var unionWithOptionalParameter2: { new (a: string, b?: number): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. strOrNum = new unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = new unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 0. var unionWithOptionalParameter3: { new (a: string, b?: number): string; } | { new (a: string): number; }; strOrNum = new unionWithOptionalParameter3('hello'); // error no call signature strOrNum = new unionWithOptionalParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = new unionWithOptionalParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = new unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var unionWithRestParameter1: { new (a: string, ...b: number[]): string; } | { new (a: string, ...b: number[]): number }; strOrNum = new unionWithRestParameter1('hello'); @@ -130,34 +130,34 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { new (a: string, ...b: number[]): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 1. strOrNum = new unionWithRestParameter2('hello', 10); // error no call signature strOrNum = new unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 3. strOrNum = new unionWithRestParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2 arguments, but got 0. var unionWithRestParameter3: { new (a: string, ...b: number[]): string; } | { new (a: string): number }; strOrNum = new unionWithRestParameter3('hello'); // error no call signature strOrNum = new unionWithRestParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 3. strOrNum = new unionWithRestParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. \ No newline at end of file +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt index 399a37c32fd..e5f4dd630ab 100644 --- a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt +++ b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt @@ -1,13 +1,13 @@ -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2554: Expected 0 type arguments, but got 1. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(5,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(8,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(10,7): error TS2420: Class 'C' incorrectly implements interface 'Function'. Property 'apply' is missing in type 'C'. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(18,10): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'C' has no compatible call signatures. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(22,10): error TS2347: Untyped function calls may not accept type arguments. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2554: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts (9 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var x = function () { return; }; var r1 = x(); ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var y: any = x; var r2 = y(); ~~~~~~~~~~~ @@ -53,7 +53,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var z: I; var r6 = z(1); // error ~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. interface callable2 { (a: T): T; @@ -62,7 +62,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c4: callable2; c4(1); ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. interface callable3 { (a: T): T; } @@ -70,6 +70,6 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c5: callable3; c5(1); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. \ No newline at end of file From 05d2f2d5d9c88a28f86d48a6d8ee49f5cdf28a3b Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 15 May 2017 15:28:55 -0700 Subject: [PATCH 205/282] Fix issue with throw in async delegator. --- src/compiler/transformers/esnext.ts | 4 ++-- .../emitter.asyncGenerators.classMethods.es2015.js | 8 ++++---- .../reference/emitter.asyncGenerators.classMethods.es5.js | 8 ++++---- ...emitter.asyncGenerators.functionDeclarations.es2015.js | 8 ++++---- .../emitter.asyncGenerators.functionDeclarations.es5.js | 8 ++++---- .../emitter.asyncGenerators.functionExpressions.es2015.js | 8 ++++---- .../emitter.asyncGenerators.functionExpressions.es5.js | 8 ++++---- ...emitter.asyncGenerators.objectLiteralMethods.es2015.js | 8 ++++---- .../emitter.asyncGenerators.objectLiteralMethods.es5.js | 8 ++++---- 9 files changed, 34 insertions(+), 34 deletions(-) diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index fef1b009ba3..81ebd0b8f5b 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -929,8 +929,8 @@ namespace ts { text: ` var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; ` }; diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js index 5f1b97b208c..d91571f93ad 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es2015.js @@ -128,8 +128,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -169,8 +169,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; class C5 { f() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js index 1fa1b19e36f..cfd7c9725e4 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js @@ -264,8 +264,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -354,8 +354,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js index 98e8291ac6a..4ca8322da9f 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es2015.js @@ -91,8 +91,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -130,8 +130,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; function f5() { return __asyncGenerator(this, arguments, function* f5_1() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js index f842a2c813a..410a25d2e16 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js @@ -218,8 +218,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -303,8 +303,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js index d491c0465f0..602fd47d38b 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es2015.js @@ -91,8 +91,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -130,8 +130,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; const f5 = function () { return __asyncGenerator(this, arguments, function* () { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js index 779d9c5340e..45d17737cef 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js @@ -218,8 +218,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -303,8 +303,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js index 22ffff01eec..760931a4342 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es2015.js @@ -111,8 +111,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -152,8 +152,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; const o5 = { f() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js index 46f3a1efac2..b5069bcea2c 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js @@ -238,8 +238,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); @@ -325,8 +325,8 @@ var __asyncValues = (this && this.__asyncIterator) || function (o) { }; var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { var i, p; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; } + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; var __values = (this && this.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; From e9ccb1664263c88702cf8223ce3dd73f7dfd4751 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 15 May 2017 15:32:14 -0700 Subject: [PATCH 206/282] Eliminate redundant exploration in type inference --- src/compiler/checker.ts | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d6f56a69b9a..26cdab1e599 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10096,21 +10096,29 @@ namespace ts { inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } + function getSymbolForInference(type: Type) { + // Exclude the static side of classes since it shares its symbol with the instance side which leads + // to false positives. + return type.flags & TypeFlags.Object && !(getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class) ? type.symbol : undefined; + } + function inferTypes(typeVariables: TypeVariable[], typeInferences: TypeInferences[], originalSource: Type, originalTarget: Type) { - let sourceStack: Type[]; - let targetStack: Type[]; + let stack: Type[]; let depth = 0; let inferiority = 0; const visited = createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source: Type, target: Type) { - for (let i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; + function isInstantiationInProcess(type: Type) { + const symbol = getSymbolForInference(type); + if (symbol) { + for (let i = 0; i < depth; i++) { + const t = stack[i]; + if (getSymbolForInference(t) === symbol) { + return true; + } } } - return false; } function inferFromTypes(source: Type, target: Type) { @@ -10240,10 +10248,10 @@ namespace ts { else { source = getApparentType(source); if (source.flags & TypeFlags.Object) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. + if (isInstantiationInProcess(target)) { return; } const key = source.id + "," + target.id; @@ -10251,12 +10259,7 @@ namespace ts { return; } visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; + (stack || (stack = []))[depth] = target; depth++; inferFromObjectTypes(source, target); depth--; From d51e467238db9229ca0620607067c083aee07cc3 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 15 May 2017 15:46:50 -0700 Subject: [PATCH 207/282] Fix #15463: use intersection types to emulate spread in generic react components (#15851) * Fix #15463: use intersection types to emulate spread in generic react components * Fix lint errors * reverse condition --- src/compiler/checker.ts | 18 ++++++-- .../tsxAttributeResolution5.errors.txt | 24 ++++++----- .../reference/tsxGenericAttributesType9.js | 40 ++++++++++++++++++ .../tsxGenericAttributesType9.symbols | 37 +++++++++++++++++ .../reference/tsxGenericAttributesType9.types | 41 +++++++++++++++++++ ...ionComponentsWithTypeArguments2.errors.txt | 18 ++++---- ...ionComponentsWithTypeArguments4.errors.txt | 18 +++++--- ...ionComponentsWithTypeArguments5.errors.txt | 12 +++++- .../jsx/tsxGenericAttributesType9.tsx | 16 ++++++++ tests/cases/fourslash/tsxQuickInfo6.ts | 2 +- tests/cases/fourslash/tsxQuickInfo7.ts | 4 +- 11 files changed, 197 insertions(+), 33 deletions(-) create mode 100644 tests/baselines/reference/tsxGenericAttributesType9.js create mode 100644 tests/baselines/reference/tsxGenericAttributesType9.symbols create mode 100644 tests/baselines/reference/tsxGenericAttributesType9.types create mode 100644 tests/cases/conformance/jsx/tsxGenericAttributesType9.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d6f56a69b9a..a2a31e3a197 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13314,6 +13314,7 @@ namespace ts { let spread: Type = emptyObjectType; let attributesArray: Symbol[] = []; let hasSpreadAnyType = false; + let typeToIntersect: Type; let explicitlySpecifyChildrenAttribute = false; const jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); @@ -13345,11 +13346,16 @@ namespace ts { attributesArray = []; attributesTable = createMap(); } - const exprType = getApparentType(checkExpression(attributeDecl.expression)); + const exprType = checkExpression(attributeDecl.expression); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } - spread = getSpreadType(spread, exprType); + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } } } @@ -13404,7 +13410,13 @@ namespace ts { } } - return hasSpreadAnyType ? anyType : createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + + const attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. diff --git a/tests/baselines/reference/tsxAttributeResolution5.errors.txt b/tests/baselines/reference/tsxAttributeResolution5.errors.txt index 0c6be5f35d0..f5af99d6f07 100644 --- a/tests/baselines/reference/tsxAttributeResolution5.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution5.errors.txt @@ -1,8 +1,10 @@ -tests/cases/conformance/jsx/file.tsx(21,16): error TS2322: Type '{ x: number; }' is not assignable to type 'Attribs1'. - Types of property 'x' are incompatible. - Type 'number' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(25,16): error TS2322: Type '{ y: string; }' is not assignable to type 'Attribs1'. - Property 'x' is missing in type '{ y: string; }'. +tests/cases/conformance/jsx/file.tsx(21,16): error TS2322: Type 'T' is not assignable to type 'Attribs1'. + Type '{ x: number; }' is not assignable to type 'Attribs1'. + Types of property 'x' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/conformance/jsx/file.tsx(25,16): error TS2322: Type 'T' is not assignable to type 'Attribs1'. + Type '{ y: string; }' is not assignable to type 'Attribs1'. + Property 'x' is missing in type '{ y: string; }'. tests/cases/conformance/jsx/file.tsx(29,8): error TS2322: Type '{}' is not assignable to type 'Attribs1'. Property 'x' is missing in type '{}'. @@ -30,16 +32,18 @@ tests/cases/conformance/jsx/file.tsx(29,8): error TS2322: Type '{}' is not assig function make2 (obj: T) { return ; // Error (x is number, not string) ~~~~~~~~ -!!! error TS2322: Type '{ x: number; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Types of property 'x' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'string'. +!!! error TS2322: Type 'T' is not assignable to type 'Attribs1'. +!!! error TS2322: Type '{ x: number; }' is not assignable to type 'Attribs1'. +!!! error TS2322: Types of property 'x' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. } function make3 (obj: T) { return ; // Error, missing x ~~~~~~~~ -!!! error TS2322: Type '{ y: string; }' is not assignable to type 'Attribs1'. -!!! error TS2322: Property 'x' is missing in type '{ y: string; }'. +!!! error TS2322: Type 'T' is not assignable to type 'Attribs1'. +!!! error TS2322: Type '{ y: string; }' is not assignable to type 'Attribs1'. +!!! error TS2322: Property 'x' is missing in type '{ y: string; }'. } diff --git a/tests/baselines/reference/tsxGenericAttributesType9.js b/tests/baselines/reference/tsxGenericAttributesType9.js new file mode 100644 index 00000000000..b7b90736ad1 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType9.js @@ -0,0 +1,40 @@ +//// [file.tsx] +import React = require('react'); + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ + return class extends React.PureComponent { + public render(): JSX.Element { + return ( + + ); + } + }; +} + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +function makeP(Ctor) { + return (function (_super) { + __extends(class_1, _super); + function class_1() { + return _super !== null && _super.apply(this, arguments) || this; + } + class_1.prototype.render = function () { + return (); + }; + return class_1; + }(React.PureComponent)); +} +exports.makeP = makeP; diff --git a/tests/baselines/reference/tsxGenericAttributesType9.symbols b/tests/baselines/reference/tsxGenericAttributesType9.symbols new file mode 100644 index 00000000000..f4df2e79408 --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType9.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ +>makeP : Symbol(makeP, Decl(file.tsx, 0, 32)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) +>Ctor : Symbol(Ctor, Decl(file.tsx, 2, 25)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>ComponentClass : Symbol(React.ComponentClass, Decl(react.d.ts, 204, 5)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>ComponentClass : Symbol(React.ComponentClass, Decl(react.d.ts, 204, 5)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) + + return class extends React.PureComponent { +>React.PureComponent : Symbol(React.PureComponent, Decl(react.d.ts, 179, 5)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>PureComponent : Symbol(React.PureComponent, Decl(react.d.ts, 179, 5)) +>P : Symbol(P, Decl(file.tsx, 2, 22)) + + public render(): JSX.Element { +>render : Symbol((Anonymous class).render, Decl(file.tsx, 3, 52)) +>JSX : Symbol(JSX, Decl(react.d.ts, 2352, 1)) +>Element : Symbol(JSX.Element, Decl(react.d.ts, 2355, 27)) + + return ( + +>Ctor : Symbol(Ctor, Decl(file.tsx, 2, 25)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol((Anonymous class), Decl(file.tsx, 3, 7)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + + ); + } + }; +} diff --git a/tests/baselines/reference/tsxGenericAttributesType9.types b/tests/baselines/reference/tsxGenericAttributesType9.types new file mode 100644 index 00000000000..a1d7efc49be --- /dev/null +++ b/tests/baselines/reference/tsxGenericAttributesType9.types @@ -0,0 +1,41 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ +>makeP :

(Ctor: React.ComponentClass

) => React.ComponentClass

+>P : P +>Ctor : React.ComponentClass

+>React : any +>ComponentClass : React.ComponentClass

+>P : P +>React : any +>ComponentClass : React.ComponentClass

+>P : P + + return class extends React.PureComponent { +>class extends React.PureComponent { public render(): JSX.Element { return ( ); } } : typeof (Anonymous class) +>React.PureComponent : React.PureComponent +>React : typeof React +>PureComponent : typeof React.PureComponent +>P : P + + public render(): JSX.Element { +>render : () => JSX.Element +>JSX : any +>Element : JSX.Element + + return ( +>( ) : JSX.Element + + +> : JSX.Element +>Ctor : React.ComponentClass

+>this.props : P & { children?: React.ReactNode; } +>this : this +>props : P & { children?: React.ReactNode; } + + ); + } + }; +} diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt index c8ff457711c..7e940116887 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments2.errors.txt @@ -1,10 +1,9 @@ -tests/cases/conformance/jsx/file.tsx(8,34): error TS2322: Type '{ ignore-prop: 10; prop: number; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. - Type '{ ignore-prop: 10; prop: number; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. +tests/cases/conformance/jsx/file.tsx(8,34): error TS2322: Type 'T & { ignore-prop: 10; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. + Type 'T & { ignore-prop: 10; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. Types of property '"ignore-prop"' are incompatible. Type '10' is not assignable to type 'string'. -tests/cases/conformance/jsx/file.tsx(13,34): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. - Type '{}' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. - Property 'prop' is missing in type '{}'. +tests/cases/conformance/jsx/file.tsx(13,34): error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. + Type 'T' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. tests/cases/conformance/jsx/file.tsx(20,19): error TS2322: Type '{ func: (a: number, b: string) => void; }' is not assignable to type 'IntrinsicAttributes & { func: (arg: number) => void; }'. Type '{ func: (a: number, b: string) => void; }' is not assignable to type '{ func: (arg: number) => void; }'. Types of property 'func' are incompatible. @@ -25,8 +24,8 @@ tests/cases/conformance/jsx/file.tsx(31,10): error TS2453: The type argument for function Bar(arg: T) { let a1 = ; ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ ignore-prop: 10; prop: number; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. -!!! error TS2322: Type '{ ignore-prop: 10; prop: number; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. +!!! error TS2322: Type 'T & { ignore-prop: 10; }' is not assignable to type 'IntrinsicAttributes & { prop: number; "ignore-prop": string; }'. +!!! error TS2322: Type 'T & { ignore-prop: 10; }' is not assignable to type '{ prop: number; "ignore-prop": string; }'. !!! error TS2322: Types of property '"ignore-prop"' are incompatible. !!! error TS2322: Type '10' is not assignable to type 'string'. } @@ -35,9 +34,8 @@ tests/cases/conformance/jsx/file.tsx(31,10): error TS2453: The type argument for function Baz(arg: T) { let a0 = ~~~~~~~~ -!!! error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. -!!! error TS2322: Type '{}' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. -!!! error TS2322: Property 'prop' is missing in type '{}'. +!!! error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { prop: {}; "ignore-prop": string; }'. +!!! error TS2322: Type 'T' is not assignable to type '{ prop: {}; "ignore-prop": string; }'. } declare function Link(l: {func: (arg: U)=>void}): JSX.Element; diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt index d9b50ef31c6..311cfaed86f 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments4.errors.txt @@ -1,9 +1,12 @@ tests/cases/conformance/jsx/file.tsx(9,33): error TS2322: Type '{ a: number; }' is not assignable to type 'IntrinsicAttributes & { b: {}; a: number; }'. Type '{ a: number; }' is not assignable to type '{ b: {}; a: number; }'. Property 'b' is missing in type '{ a: number; }'. -tests/cases/conformance/jsx/file.tsx(10,33): error TS2322: Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. - Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. - Property 'a' is missing in type '{ b: number; }'. +tests/cases/conformance/jsx/file.tsx(10,33): error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. + Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. + Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. + Type 'T' is not assignable to type '{ b: number; a: {}; }'. + Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. + Property 'a' is missing in type '{ b: number; }'. ==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== @@ -22,7 +25,10 @@ tests/cases/conformance/jsx/file.tsx(10,33): error TS2322: Type '{ b: number; }' !!! error TS2322: Property 'b' is missing in type '{ a: number; }'. let a2 = // missing a ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. -!!! error TS2322: Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. -!!! error TS2322: Property 'a' is missing in type '{ b: number; }'. +!!! error TS2322: Type 'T' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. +!!! error TS2322: Type '{ b: number; }' is not assignable to type 'IntrinsicAttributes & { b: number; a: {}; }'. +!!! error TS2322: Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. +!!! error TS2322: Type 'T' is not assignable to type '{ b: number; a: {}; }'. +!!! error TS2322: Type '{ b: number; }' is not assignable to type '{ b: number; a: {}; }'. +!!! error TS2322: Property 'a' is missing in type '{ b: number; }'. } \ No newline at end of file diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt index b92375797e7..57a2ae556f7 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt @@ -1,7 +1,11 @@ +tests/cases/conformance/jsx/file.tsx(15,14): error TS2605: JSX element type 'Element' is not a constructor function for JSX elements. + Property 'render' is missing in type 'Element'. +tests/cases/conformance/jsx/file.tsx(15,15): error TS2453: The type argument for type parameter 'U' cannot be inferred from the usage. Consider specifying the type arguments explicitly. + Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate '"hello"'. tests/cases/conformance/jsx/file.tsx(16,42): error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & { prop: number; }'. -==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== import React = require('react') declare function Component(l: U): JSX.Element; @@ -17,6 +21,12 @@ tests/cases/conformance/jsx/file.tsx(16,42): error TS2339: Property 'prop1' does let a1 = ; // U is number let a2 = ; // U is number let a3 = ; // U is "hello" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2605: JSX element type 'Element' is not a constructor function for JSX elements. +!!! error TS2605: Property 'render' is missing in type 'Element'. + ~~~~~~~~~~~~~~~~~ +!!! error TS2453: The type argument for type parameter 'U' cannot be inferred from the usage. Consider specifying the type arguments explicitly. +!!! error TS2453: Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate '"hello"'. let a4 = ; // U is "hello" ~~~~~~~~~~~~~ !!! error TS2339: Property 'prop1' does not exist on type 'IntrinsicAttributes & { prop: number; }'. diff --git a/tests/cases/conformance/jsx/tsxGenericAttributesType9.tsx b/tests/cases/conformance/jsx/tsxGenericAttributesType9.tsx new file mode 100644 index 00000000000..a9466a43983 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxGenericAttributesType9.tsx @@ -0,0 +1,16 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +export function makeP

(Ctor: React.ComponentClass

): React.ComponentClass

{ + return class extends React.PureComponent { + public render(): JSX.Element { + return ( + + ); + } + }; +} \ No newline at end of file diff --git a/tests/cases/fourslash/tsxQuickInfo6.ts b/tests/cases/fourslash/tsxQuickInfo6.ts index 88d9435e801..2b65dc7667a 100644 --- a/tests/cases/fourslash/tsxQuickInfo6.ts +++ b/tests/cases/fourslash/tsxQuickInfo6.ts @@ -15,5 +15,5 @@ verify.quickInfos({ 1: "function ComponentSpecific(l: {\n prop: number;\n}): any", - 2: "function ComponentSpecific<\"hello\">(l: {\n prop: \"hello\";\n}): any" + 2: "function ComponentSpecific(l: {\n prop: U;\n}): any" }); diff --git a/tests/cases/fourslash/tsxQuickInfo7.ts b/tests/cases/fourslash/tsxQuickInfo7.ts index 3e66fb655f1..cf08aa53e98 100644 --- a/tests/cases/fourslash/tsxQuickInfo7.ts +++ b/tests/cases/fourslash/tsxQuickInfo7.ts @@ -24,6 +24,6 @@ verify.quickInfos({ 3: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", 4: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", 5: "function OverloadComponent(): any (+2 overloads)", - 6: "function OverloadComponent(attr: {\n b: number;\n a: boolean;\n}): any (+2 overloads)", - 7: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)" + 6: "function OverloadComponent(): any (+2 overloads)", + 7: "function OverloadComponent(): any (+2 overloads)", }); From 35a9be3b6c703ed059d15abf5cf06583c62669d7 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 16:22:04 -0700 Subject: [PATCH 208/282] Improve arity errors for all calls Not just ones with a single call signature. This is pretty great! --- src/compiler/checker.ts | 47 +++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5be1fb633cd..e7e871f12b3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15369,28 +15369,33 @@ namespace ts { reportNoCommonSupertypeError(inferenceCandidates, (node).tagName || (node).expression || (node).tag, diagnosticChainHead); } } + else if (typeArguments && every(signatures, sig => length(sig.typeParameters) !== typeArguments.length)) { + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + for (const sig of signatures) { + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, length(sig.typeParameters)); + } + const paramMessage = max > min ? `${min}-${max}` : min.toString(); + reportError(Diagnostics.Expected_0_type_arguments_but_got_1, paramMessage, typeArguments.length.toString()); + } + else if (args) { + const argMessage = getSpreadArgumentIndex(args) > -1 ? + "a minimum of " + (args.length - 1) : + args.length.toString(); + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + for (const sig of signatures) { + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + const paramMessage = some(signatures, sig => sig.hasRestParameter) ? "at least " + min : + min < max ? `${min}-${max}` : + min.toString(); + reportError(Diagnostics.Expected_0_arguments_but_got_1, paramMessage, argMessage); + } else { - if (signatures.length === 1) { - if (typeArguments && typeArguments.length !== length(signatures[0].typeParameters)) { - const minTypeArgumentCount = getMinTypeArgumentCount(signatures[0].typeParameters); - const paramMessage = length(signatures[0].typeParameters) > minTypeArgumentCount ? - `${minTypeArgumentCount}-${length(signatures[0].typeParameters)}` : - minTypeArgumentCount.toString(); - reportError(Diagnostics.Expected_0_type_arguments_but_got_1, paramMessage, typeArguments.length.toString()); - } - else { - const argMessage = getSpreadArgumentIndex(args) > -1 ? - "a minimum of " + (args.length - 1) : - args.length.toString(); - const paramMessage = signatures[0].hasRestParameter ? "at least " + signatures[0].minArgumentCount : - signatures[0].minArgumentCount < signatures[0].parameters.length ? `${signatures[0].minArgumentCount}-${signatures[0].parameters.length}` : - signatures[0].minArgumentCount.toString(); - reportError(Diagnostics.Expected_0_arguments_but_got_1, paramMessage, argMessage); - } - } - else { - reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); - } + reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } // No signature was applicable. We have already reported the errors for the invalid signature. From c9308fc6109d74575de30913be00e53ae4a9c1ce Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 15 May 2017 16:22:35 -0700 Subject: [PATCH 209/282] Update baselines --- .../assigningFromObjectToAnythingElse.errors.txt | 8 ++++---- ...opedSameNameFunctionDeclarationES5.errors.txt | 12 ++++++------ ...opedSameNameFunctionDeclarationES6.errors.txt | 12 ++++++------ .../reference/classWithConstructors.errors.txt | 16 ++++++++-------- ...edClassWithoutExplicitConstructor2.errors.txt | 8 ++++---- .../reference/functionOverloads29.errors.txt | 4 ++-- .../reference/functionOverloads34.errors.txt | 4 ++-- .../reference/functionOverloads37.errors.txt | 4 ++-- tests/baselines/reference/overload1.errors.txt | 8 ++++---- .../reference/overloadResolution.errors.txt | 4 ++-- ...verloadResolutionClassConstructors.errors.txt | 12 ++++++------ .../overloadResolutionConstructors.errors.txt | 4 ++-- ...verloadsAndTypeArgumentArityErrors.errors.txt | 10 +++++----- .../parserConstructorAmbiguity3.errors.txt | 4 ++-- .../reference/recursiveFunctionTypes.errors.txt | 8 ++++---- ...lateStringsWithOverloadResolution1.errors.txt | 8 ++++---- ...StringsWithOverloadResolution1_ES6.errors.txt | 8 ++++---- ...lateStringsWithOverloadResolution3.errors.txt | 4 ++-- ...StringsWithOverloadResolution3_ES6.errors.txt | 4 ++-- ...nInCallExpressionWithTypeArguments.errors.txt | 4 ++-- .../reference/unionTypeCallSignatures.errors.txt | 4 ++-- .../unionTypeConstructSignatures.errors.txt | 4 ++-- 22 files changed, 77 insertions(+), 77 deletions(-) diff --git a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt index d3395c7ebc9..8c2fdd533f0 100644 --- a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt +++ b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(3,1): error TS2322: Type 'Object' is not assignable to type 'RegExp'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'exec' is missing in type 'Object'. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2554: Expected 0 type arguments, but got 1. tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Type 'Object' is not assignable to type 'Error'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'name' is missing in type 'Object'. @@ -19,10 +19,10 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Ty var a: String = Object.create(""); ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var c: String = Object.create(1); ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. var w: Error = new Object(); ~ diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt index 1ed2175833a..fe9bc6700fb 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(3,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(5,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(5,9): error TS2553: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(8,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(12,5): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(10,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(12,5): error TS2553: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error TS2553: Expected 1 arguments, but got 0. @@ -15,7 +15,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } else { function foo() { } // duplicate function @@ -24,11 +24,11 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. foo(); } foo(10); diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt index 0669f2bdebc..6df85e1495a 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(3,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(5,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(5,9): error TS2553: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(8,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(10,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(12,5): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(10,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(12,5): error TS2553: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error TS2553: Expected 1 arguments, but got 0. @@ -15,7 +15,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } else { function foo() { } // duplicate @@ -24,11 +24,11 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(); foo(10);// not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. } foo(10); // not ok ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0 arguments, but got 1. foo(); } foo(10); diff --git a/tests/baselines/reference/classWithConstructors.errors.txt b/tests/baselines/reference/classWithConstructors.errors.txt index a983ff104d3..b637775876a 100644 --- a/tests/baselines/reference/classWithConstructors.errors.txt +++ b/tests/baselines/reference/classWithConstructors.errors.txt @@ -1,9 +1,9 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(6,13): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(15,14): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(21,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(15,14): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(21,13): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(31,13): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(40,14): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(46,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(40,14): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(46,13): error TS2553: Expected 1-2 arguments, but got 0. ==== tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts (6 errors) ==== @@ -25,7 +25,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var c4 = new C2(''); // ok var c5 = new C2(1); // ok @@ -33,7 +33,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var d2 = new D(1); // ok var d3 = new D(''); // ok } @@ -56,7 +56,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. var c4 = new C2(''); // ok var c5 = new C2(1, 2); // ok @@ -64,7 +64,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. var d2 = new D(1); // ok var d3 = new D(''); // ok } \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt index b699fb7c89e..d89786b71bf 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(13,9): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(30,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(13,9): error TS2553: Expected 1-3 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(30,9): error TS2553: Expected 1-3 arguments, but got 0. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts (2 errors) ==== @@ -17,7 +17,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 0. var r2 = new Derived(1); var r3 = new Derived(1, 2); var r4 = new Derived(1, 2, 3); @@ -36,7 +36,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 0. var d2 = new D(new Date()); // ok var d3 = new D(new Date(), new Date()); var d4 = new D(new Date(), new Date(), new Date()); \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads29.errors.txt b/tests/baselines/reference/functionOverloads29.errors.txt index 763405e351b..327eba07aba 100644 --- a/tests/baselines/reference/functionOverloads29.errors.txt +++ b/tests/baselines/reference/functionOverloads29.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads29.ts(4,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionOverloads29.ts(4,9): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads29.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads29.ts(4,9): error TS2346: Supplied paramet function foo(bar:any):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads34.errors.txt b/tests/baselines/reference/functionOverloads34.errors.txt index ccd771d2130..6c7d1085981 100644 --- a/tests/baselines/reference/functionOverloads34.errors.txt +++ b/tests/baselines/reference/functionOverloads34.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads34.ts(4,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionOverloads34.ts(4,9): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads34.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads34.ts(4,9): error TS2346: Supplied paramet function foo(bar:{a:any;}):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads37.errors.txt b/tests/baselines/reference/functionOverloads37.errors.txt index 742e1bedb22..1a7ed43a8c2 100644 --- a/tests/baselines/reference/functionOverloads37.errors.txt +++ b/tests/baselines/reference/functionOverloads37.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads37.ts(4,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/functionOverloads37.ts(4,9): error TS2553: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads37.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads37.ts(4,9): error TS2346: Supplied paramet function foo(bar:{a:any;}[]):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/overload1.errors.txt b/tests/baselines/reference/overload1.errors.txt index a88b4f81519..100c92d4002 100644 --- a/tests/baselines/reference/overload1.errors.txt +++ b/tests/baselines/reference/overload1.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/overload1.ts(27,5): error TS2322: Type 'C' is not assignable to type 'string'. tests/cases/compiler/overload1.ts(29,1): error TS2322: Type 'number' is not assignable to type 'string'. -tests/cases/compiler/overload1.ts(31,3): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/overload1.ts(32,3): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/overload1.ts(31,3): error TS2553: Expected 1-2 arguments, but got 3. +tests/cases/compiler/overload1.ts(32,3): error TS2553: Expected 1-2 arguments, but got 0. tests/cases/compiler/overload1.ts(33,1): error TS2322: Type 'C' is not assignable to type 'string'. tests/cases/compiler/overload1.ts(34,9): error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. @@ -43,10 +43,10 @@ tests/cases/compiler/overload1.ts(34,9): error TS2345: Argument of type '2' is n var z:string=x.g(x.g(3,3)); // good z=x.g(2,2,2); // no match ~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 3. z=x.g(); // no match ~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 0. z=x.g(new O.B()); // ambiguous (up and down conversion) ~ !!! error TS2322: Type 'C' is not assignable to type 'string'. diff --git a/tests/baselines/reference/overloadResolution.errors.txt b/tests/baselines/reference/overloadResolution.errors.txt index b8b2cdfe888..f122b74d55e 100644 --- a/tests/baselines/reference/overloadResolution.errors.txt +++ b/tests/baselines/reference/overloadResolution.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(27,5): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(41,11): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2554: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(70,21): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(71,21): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(81,5): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -79,7 +79,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(91,22): // Generic overloads with differing arity called with type argument count that doesn't match any overload fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints function fn4(n: T, m: U); diff --git a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt index 4c8e9b2513a..998fa1fa96d 100644 --- a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2554: Expected 3 type arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2554: Expected 3 type arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2554: Expected 3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(73,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(74,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(75,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. @@ -78,16 +78,16 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstru // Generic overloads with differing arity called with type arguments matching each overload type parameter count new fn3(4); // Error ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 type arguments, but got 1. new fn3('', '', ''); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 type arguments, but got 2. new fn3('', '', 3); // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints class fn4 { diff --git a/tests/baselines/reference/overloadResolutionConstructors.errors.txt b/tests/baselines/reference/overloadResolutionConstructors.errors.txt index 9a112eaf2ef..c8741795245 100644 --- a/tests/baselines/reference/overloadResolutionConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionConstructors.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(43,15): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2554: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(77,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(78,25): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(88,9): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -83,7 +83,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints interface fn4 { diff --git a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt index 64faaf7e8c1..661def113d4 100644 --- a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt +++ b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2554: Expected 0-2 type arguments, but got 3. tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2554: Expected 0-2 type arguments, but got 3. ==== tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts (3 errors) ==== @@ -10,9 +10,9 @@ tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2350: Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0-2 type arguments, but got 3. new Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2350: Only a void function can be called with the 'new' keyword. \ No newline at end of file +!!! error TS2554: Expected 0-2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt index 821451c00c8..b34235df7fb 100644 --- a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt +++ b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2554: Expected 0 type arguments, but got 1. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,10): error TS2304: Cannot find name 'A'. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,12): error TS1005: '(' expected. @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts (3 errors) ==== new Date ~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2554: Expected 0 type arguments, but got 1. ~ !!! error TS2304: Cannot find name 'A'. diff --git a/tests/baselines/reference/recursiveFunctionTypes.errors.txt b/tests/baselines/reference/recursiveFunctionTypes.errors.txt index 8a454133a82..72dd792765f 100644 --- a/tests/baselines/reference/recursiveFunctionTypes.errors.txt +++ b/tests/baselines/reference/recursiveFunctionTypes.errors.txt @@ -8,9 +8,9 @@ tests/cases/compiler/recursiveFunctionTypes.ts(17,5): error TS2322: Type '() => tests/cases/compiler/recursiveFunctionTypes.ts(22,5): error TS2345: Argument of type '3' is not assignable to parameter of type '(t: typeof g) => void'. tests/cases/compiler/recursiveFunctionTypes.ts(25,1): error TS2322: Type '3' is not assignable to type '() => any'. tests/cases/compiler/recursiveFunctionTypes.ts(30,10): error TS2394: Overload signature is not compatible with function implementation. -tests/cases/compiler/recursiveFunctionTypes.ts(33,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/recursiveFunctionTypes.ts(33,1): error TS2553: Expected 0-1 arguments, but got 2. tests/cases/compiler/recursiveFunctionTypes.ts(34,4): error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f6; (a: typeof f6): () => number; }'. -tests/cases/compiler/recursiveFunctionTypes.ts(42,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/recursiveFunctionTypes.ts(42,1): error TS2553: Expected 0-1 arguments, but got 2. tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f7; (a: typeof f7): () => number; (a: number): number; (a?: typeof f7): typeof f7; }'. @@ -68,7 +68,7 @@ tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of f6("", 3); // error (arity mismatch) ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-1 arguments, but got 2. f6(""); // ok (function takes an any param) ~~ !!! error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f6; (a: typeof f6): () => number; }'. @@ -81,7 +81,7 @@ tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of f7("", 3); // error (arity mismatch) ~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 0-1 arguments, but got 2. f7(""); // ok (function takes an any param) ~~ !!! error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f7; (a: typeof f7): () => number; (a: number): number; (a?: typeof f7): typeof f7; }'. diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt index e9c9e0ed6e0..d105ea1efec 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt @@ -4,9 +4,9 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(11,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(12,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(13,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(14,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(14,9): error TS2553: Expected 1-3 arguments, but got 4. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(19,20): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(21,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(21,9): error TS2553: Expected 1-3 arguments, but got 4. ==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts (8 errors) ==== @@ -36,7 +36,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio !!! error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. var f = foo([], 1, 2, 3); // any (with error) ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 4. var u = foo ``; // number var v = foo `${1}`; // string @@ -47,5 +47,5 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio var y = foo `${1}${"2"}`; // {} var z = foo `${1}${2}${3}`; // any (with error) ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 4. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt index d7817e32ee0..85e6c35ec4b 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt @@ -4,9 +4,9 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(11,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(12,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(13,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(14,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(14,9): error TS2553: Expected 1-3 arguments, but got 4. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(19,20): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(21,9): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(21,9): error TS2553: Expected 1-3 arguments, but got 4. ==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts (8 errors) ==== @@ -36,7 +36,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio !!! error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. var f = foo([], 1, 2, 3); // any (with error) ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 4. var u = foo ``; // number var v = foo `${1}`; // string @@ -47,5 +47,5 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio var y = foo `${1}${"2"}`; // {} var z = foo `${1}${2}${3}`; // any (with error) ~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-3 arguments, but got 4. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt index 444985cb380..169cffd28cc 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(9,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(18,4): error TS2339: Property 'foo' does not exist on type 'Date'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(44,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(44,1): error TS2553: Expected 2-4 arguments, but got 1. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(62,9): error TS2345: Argument of type 'true' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(63,18): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(69,18): error TS2339: Property 'toFixed' does not exist on type 'string'. @@ -56,7 +56,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio // Generic overloads with differing arity tagging with argument count that doesn't match any overload fn3 ``; // Error ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2-4 arguments, but got 1. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt index 7329ade1b64..dcbc5e1cd79 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(9,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(18,4): error TS2339: Property 'foo' does not exist on type 'Date'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(44,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(44,1): error TS2553: Expected 2-4 arguments, but got 1. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(62,9): error TS2345: Argument of type 'true' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(63,18): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(69,18): error TS2339: Property 'toFixed' does not exist on type 'string'. @@ -56,7 +56,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio // Generic overloads with differing arity tagging with argument count that doesn't match any overload fn3 ``; // Error ~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 2-4 arguments, but got 1. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt b/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt index 6f60a8f1be7..4043276dfc5 100644 --- a/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt +++ b/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts(2,20): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts(2,20): error TS2553: Expected 1-2 arguments, but got 1. ==== tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts (1 errors) ==== class C { public foo() { [1,2,3].map((x) => { return this; })} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1-2 arguments, but got 1. } \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures.errors.txt b/tests/baselines/reference/unionTypeCallSignatures.errors.txt index 0172de7b351..4bad49206ee 100644 --- a/tests/baselines/reference/unionTypeCallSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(9,43): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(10,29): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(15,29): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(16,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(19,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(20,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(21,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. @@ -55,7 +55,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var unionOfDifferentParameterTypes: { (a: number): number; } | { (a: string): Date; }; unionOfDifferentParameterTypes(10);// error - no call signatures diff --git a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt index a84fe952e67..18f08209048 100644 --- a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(9,47): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(10,33): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(15,33): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(16,1): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(19,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(20,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(21,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. @@ -54,7 +54,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. new unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2553: Expected 1 arguments, but got 0. var unionOfDifferentParameterTypes: { new (a: number): number; } | { new (a: string): Date; }; new unionOfDifferentParameterTypes(10);// error - no call signatures From bba41a8a0c9740ff57eed37ea281c4a6b046c21b Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 15 May 2017 18:42:49 -0700 Subject: [PATCH 210/282] avoid ascii escaping literal text --- src/compiler/checker.ts | 8 +++++--- src/compiler/emitter.ts | 4 +++- src/compiler/types.ts | 1 + src/compiler/utilities.ts | 19 +++++++++---------- tests/cases/compiler/unicodeStringLiteral.ts | 1 + ...ImplementInterfaceIndexSignaturesString.ts | 4 ++-- ...mplementInterfaceInheritsAbstractMethod.ts | 4 ++-- ...ssImplementInterfaceMultipleImplements2.ts | 4 ++-- 8 files changed, 25 insertions(+), 20 deletions(-) create mode 100644 tests/cases/compiler/unicodeStringLiteral.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a7ca6769082..d9b3c52b73d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2385,7 +2385,7 @@ namespace ts { return createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (TypeFlags.StringLiteral)) { - return createLiteralTypeNode((createLiteral((type).text))); + return createLiteralTypeNode(setEmitFlags(createLiteral((type).text), EmitFlags.NoAsciiEscaping)); } if (type.flags & (TypeFlags.NumberLiteral)) { return createLiteralTypeNode((createNumericLiteral((type).text))); @@ -2783,7 +2783,9 @@ namespace ts { let returnTypeNode: TypeNode; if (signature.typePredicate) { const typePredicate = signature.typePredicate; - const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? createIdentifier((typePredicate).parameterName) : createThisTypeNode(); + const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? + setEmitFlags(createIdentifier((typePredicate).parameterName), EmitFlags.NoAsciiEscaping) : + createThisTypeNode(); const typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = createTypePredicateNode(parameterName, typeNode); } @@ -2894,7 +2896,7 @@ namespace ts { } const symbolName = getNameOfSymbol(symbol, context); - const identifier = createIdentifier(symbolName, typeParameterNodes); + const identifier = setEmitFlags(createIdentifier(symbolName, typeParameterNodes), EmitFlags.NoAsciiEscaping); return index > 0 ? createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 8ec03e90c77..826b636e71e 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2653,7 +2653,9 @@ namespace ts { if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { const textSourceNode = (node).textSourceNode; if (isIdentifier(textSourceNode)) { - return "\"" + escapeNonAsciiCharacters(escapeString(getTextOfNode(textSourceNode))) + "\""; + return getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? + `"${escapeString(getTextOfNode(textSourceNode))}"` : + `"${escapeNonAsciiCharacters(escapeString(getTextOfNode(textSourceNode)))}"`; } else { return getLiteralTextOfNode(textSourceNode); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index cf204d158a1..4bc97c56c00 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3985,6 +3985,7 @@ namespace ts { NoHoisting = 1 << 21, // Do not hoist this declaration in --module system HasEndOfDeclarationMarker = 1 << 22, // Declaration has an associated NotEmittedStatement to mark the end of the declaration Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. + NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions. } export interface EmitHelper { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 80daf383639..9dac18eec89 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -328,19 +328,22 @@ namespace ts { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + const escapeText = getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? + (text: string) => escapeString(text) : + (text: string) => escapeNonAsciiCharacters(escapeString(text)); // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case SyntaxKind.StringLiteral: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case SyntaxKind.NoSubstitutionTemplateLiteral: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case SyntaxKind.TemplateHead: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case SyntaxKind.TemplateMiddle: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case SyntaxKind.TemplateTail: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case SyntaxKind.NumericLiteral: return node.text; } @@ -348,10 +351,6 @@ namespace ts { Debug.fail(`Literal kind '${node.kind}' not accounted for.`); } - function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; - } - // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' export function escapeIdentifier(identifier: string): string { return identifier.length >= 2 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ ? "_" + identifier : identifier; diff --git a/tests/cases/compiler/unicodeStringLiteral.ts b/tests/cases/compiler/unicodeStringLiteral.ts new file mode 100644 index 00000000000..fa2e1283309 --- /dev/null +++ b/tests/cases/compiler/unicodeStringLiteral.ts @@ -0,0 +1 @@ +var ੳ = "Ü­ਲĭ"; \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts index 4b595c6eda7..9d42faada36 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceIndexSignaturesString.ts @@ -1,11 +1,11 @@ /// //// interface I { -//// [x: string]: X; +//// [Ƚ: string]: X; //// } //// //// class C implements I {[| |]} verify.rangeAfterCodeFix(` - [x: string]: number; + [Ƚ: string]: number; `); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts index c141592823a..7bb230a2dfb 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceInheritsAbstractMethod.ts @@ -2,12 +2,12 @@ //// abstract class C1 { } //// abstract class C2 { -//// abstract f1(); +//// abstract fA(); //// } //// interface I1 extends C1, C2 { } //// class C3 implements I1 {[| |]} -verify.rangeAfterCodeFix(`f1(){ +verify.rangeAfterCodeFix(`fA(){ throw new Error("Method not implemented."); } `); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts index e5100b88f6c..946b6495c5f 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceMultipleImplements2.ts @@ -4,7 +4,7 @@ //// x: number; //// } //// interface I2 { -//// y: number; +//// y: "𣋝ઢȴ¬⏊"; //// } //// //// class C implements I1,I2 {[| @@ -12,7 +12,7 @@ //// } verify.rangeAfterCodeFix(` -y: number; +y: "𣋝ઢȴ¬⏊"; `); verify.not.codeFixAvailable(); From a9ab30c068e3096a6586980d5c3dd89ab63f1851 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 15 May 2017 18:43:06 -0700 Subject: [PATCH 211/282] revert baselines --- .../reference/unicodeExtendedEscapesInStrings06_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings06_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings08_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings08_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings09_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings09_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings10_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings10_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings11_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings11_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings13_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings13_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings15_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings15_ES6.types | 2 +- .../reference/unicodeExtendedEscapesInStrings16_ES5.types | 2 +- .../reference/unicodeExtendedEscapesInStrings16_ES6.types | 2 +- tests/baselines/reference/unicodeStringLiteral.js | 5 +++++ tests/baselines/reference/unicodeStringLiteral.symbols | 4 ++++ tests/baselines/reference/unicodeStringLiteral.types | 5 +++++ 19 files changed, 30 insertions(+), 16 deletions(-) create mode 100644 tests/baselines/reference/unicodeStringLiteral.js create mode 100644 tests/baselines/reference/unicodeStringLiteral.symbols create mode 100644 tests/baselines/reference/unicodeStringLiteral.types diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types index e6942df5d1e..0c742aaf7bd 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES5.types @@ -3,5 +3,5 @@ // 1. Assert: 0 ≤ cp ≤ 0x10FFFF. var x = "\u{10FFFF}"; >x : string ->"\u{10FFFF}" : "\uDBFF\uDFFF" +>"\u{10FFFF}" : "􏿿" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types index 82cc1fa622b..6b98c0c98a7 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings06_ES6.types @@ -3,5 +3,5 @@ // 1. Assert: 0 ≤ cp ≤ 0x10FFFF. var x = "\u{10FFFF}"; >x : string ->"\u{10FFFF}" : "\uDBFF\uDFFF" +>"\u{10FFFF}" : "􏿿" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types index 9c316cca313..0007b758817 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES5.types @@ -4,5 +4,5 @@ // (FFFF == 65535) var x = "\u{FFFF}"; >x : string ->"\u{FFFF}" : "\uFFFF" +>"\u{FFFF}" : "￿" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types index a5982a77c67..aedd2f72ef9 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings08_ES6.types @@ -4,5 +4,5 @@ // (FFFF == 65535) var x = "\u{FFFF}"; >x : string ->"\u{FFFF}" : "\uFFFF" +>"\u{FFFF}" : "￿" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types index 7508721f141..daf8a776e8a 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES5.types @@ -4,5 +4,5 @@ // (10000 == 65536) var x = "\u{10000}"; >x : string ->"\u{10000}" : "\uD800\uDC00" +>"\u{10000}" : "𐀀" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types index 5f05276ed33..0963f552c96 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings09_ES6.types @@ -4,5 +4,5 @@ // (10000 == 65536) var x = "\u{10000}"; >x : string ->"\u{10000}" : "\uD800\uDC00" +>"\u{10000}" : "𐀀" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types index a5422cc7a92..a4977300e65 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES5.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{D800}"; >x : string ->"\u{D800}" : "\uD800" +>"\u{D800}" : "�" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types index 2fcdd0547ee..6d6d0112f08 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings10_ES6.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{D800}"; >x : string ->"\u{D800}" : "\uD800" +>"\u{D800}" : "�" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types index b26387baaec..74e6817c85a 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES5.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{DC00}"; >x : string ->"\u{DC00}" : "\uDC00" +>"\u{DC00}" : "�" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types index cd010529996..c1b3f372dab 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings11_ES6.types @@ -5,5 +5,5 @@ // this is a useful edge-case test. var x = "\u{DC00}"; >x : string ->"\u{DC00}" : "\uDC00" +>"\u{DC00}" : "�" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types index 68eb2fe8de1..224e81adec5 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES5.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings13_ES5.ts === var x = "\u{DDDDD}"; >x : string ->"\u{DDDDD}" : "\uDB37\uDDDD" +>"\u{DDDDD}" : "󝷝" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types index 4ad8d2e3f3d..e69b2af435c 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings13_ES6.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings13_ES6.ts === var x = "\u{DDDDD}"; >x : string ->"\u{DDDDD}" : "\uDB37\uDDDD" +>"\u{DDDDD}" : "󝷝" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types index 8da56115188..1973bb3790b 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES5.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings15_ES5.ts === var x = "\u{abcd}\u{ef12}\u{3456}\u{7890}"; >x : string ->"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" +>"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "ꯍ㑖碐" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types index 613d91afae2..16ae5177f51 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings15_ES6.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings15_ES6.ts === var x = "\u{abcd}\u{ef12}\u{3456}\u{7890}"; >x : string ->"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" +>"\u{abcd}\u{ef12}\u{3456}\u{7890}" : "ꯍ㑖碐" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types index 1b29651e2d7..1ae9d9ef3d5 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES5.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings16_ES5.ts === var x = "\u{ABCD}\u{EF12}\u{3456}\u{7890}"; >x : string ->"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" +>"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "ꯍ㑖碐" diff --git a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types index addf7dedff4..a4abc5bdeae 100644 --- a/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types +++ b/tests/baselines/reference/unicodeExtendedEscapesInStrings16_ES6.types @@ -1,5 +1,5 @@ === tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings16_ES6.ts === var x = "\u{ABCD}\u{EF12}\u{3456}\u{7890}"; >x : string ->"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "\uABCD\uEF12\u3456\u7890" +>"\u{ABCD}\u{EF12}\u{3456}\u{7890}" : "ꯍ㑖碐" diff --git a/tests/baselines/reference/unicodeStringLiteral.js b/tests/baselines/reference/unicodeStringLiteral.js new file mode 100644 index 00000000000..c69f7aa7e99 --- /dev/null +++ b/tests/baselines/reference/unicodeStringLiteral.js @@ -0,0 +1,5 @@ +//// [unicodeStringLiteral.ts] +var ੳ = "Ü­ਲĭ"; + +//// [unicodeStringLiteral.js] +var ੳ = "Ü­ਲĭ"; diff --git a/tests/baselines/reference/unicodeStringLiteral.symbols b/tests/baselines/reference/unicodeStringLiteral.symbols new file mode 100644 index 00000000000..f48111c0608 --- /dev/null +++ b/tests/baselines/reference/unicodeStringLiteral.symbols @@ -0,0 +1,4 @@ +=== tests/cases/compiler/unicodeStringLiteral.ts === +var ੳ = "Ü­ਲĭ"; +>ੳ : Symbol(ੳ, Decl(unicodeStringLiteral.ts, 0, 3)) + diff --git a/tests/baselines/reference/unicodeStringLiteral.types b/tests/baselines/reference/unicodeStringLiteral.types new file mode 100644 index 00000000000..e98f5987ed3 --- /dev/null +++ b/tests/baselines/reference/unicodeStringLiteral.types @@ -0,0 +1,5 @@ +=== tests/cases/compiler/unicodeStringLiteral.ts === +var ੳ = "Ü­ਲĭ"; +>ੳ : string +>"Ü­ਲĭ" : "Ü­ਲ\u000Eĭ" + From b2176c1872ca67fe7a97491639a34942e5c35a65 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Mon, 15 May 2017 19:11:36 -0700 Subject: [PATCH 212/282] no ascii escaping in param names --- src/compiler/checker.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d9b3c52b73d..0f2e5e9e0ff 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2818,7 +2818,7 @@ namespace ts { const modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(getSynthesizedClone); const dotDotDotToken = isRestParameter(parameterDeclaration) ? createToken(SyntaxKind.DotDotDotToken) : undefined; const name = parameterDeclaration.name.kind === SyntaxKind.Identifier ? - getSynthesizedClone(parameterDeclaration.name) : + setEmitFlags(getSynthesizedClone(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : cloneBindingName(parameterDeclaration.name); const questionToken = isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : undefined; @@ -2846,7 +2846,7 @@ namespace ts { if (clone.kind === SyntaxKind.BindingElement) { (clone).initializer = undefined; } - return setEmitFlags(clone, EmitFlags.SingleLine); + return setEmitFlags(clone, EmitFlags.SingleLine | EmitFlags.NoAsciiEscaping); } } } From 2d3c7bae24926ba1ef63722bab813c39bc81b2bf Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 16 May 2017 07:10:38 -0700 Subject: [PATCH 213/282] break -> continue --- src/services/utilities.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/utilities.ts b/src/services/utilities.ts index e452d18de48..ed28daf0197 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -659,7 +659,7 @@ namespace ts { const start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); if (start > position) { - break; + continue; } const end = child.getEnd(); From 381f056c68ef70826c9e8f64e8f43e346ed9eb16 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 16 May 2017 08:05:07 -0700 Subject: [PATCH 214/282] Split error messages so they are localisable --- src/compiler/checker.ts | 17 +++++++++++------ src/compiler/diagnosticMessages.json | 14 +++++++++++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e7e871f12b3..73147bb99bb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15380,19 +15380,24 @@ namespace ts { reportError(Diagnostics.Expected_0_type_arguments_but_got_1, paramMessage, typeArguments.length.toString()); } else if (args) { - const argMessage = getSpreadArgumentIndex(args) > -1 ? - "a minimum of " + (args.length - 1) : - args.length.toString(); let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; for (const sig of signatures) { min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } - const paramMessage = some(signatures, sig => sig.hasRestParameter) ? "at least " + min : + /////////// + const hasRestParameter = some(signatures, sig => sig.hasRestParameter); + const hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + const paramCount = hasRestParameter ? min : min < max ? `${min}-${max}` : - min.toString(); - reportError(Diagnostics.Expected_0_arguments_but_got_1, paramMessage, argMessage); + min; + const argCount = args.length - (hasSpreadArgument ? 1 : 0); + const error = hasRestParameter && hasSpreadArgument ? Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + Diagnostics.Expected_0_arguments_but_got_1; + reportError(error, paramCount.toString(), argCount.toString()); } else { reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 849b780380f..0f4d373c05b 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1859,10 +1859,22 @@ "category": "Error", "code": 2553 }, - "Expected {0} type arguments, but got {1}.": { + "Expected at least {0} arguments, but got {1}.": { "category": "Error", "code": 2554 }, + "Expected {0} arguments, but got a minimum of {1}.": { + "category": "Error", + "code": 2555 + }, + "Expected at least {0} arguments, but got a minimum of {1}.": { + "category": "Error", + "code": 2556 + }, + "Expected {0} type arguments, but got {1}.": { + "category": "Error", + "code": 2557 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 From ca61755eb50fa8fd280421e48b5d6b8c385d11e9 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 16 May 2017 08:07:04 -0700 Subject: [PATCH 215/282] Update baselines with new error numbers --- ...signingFromObjectToAnythingElse.errors.txt | 8 +-- ...hIncorrectNumberOfTypeArguments.errors.txt | 56 +++++++++---------- ...enericFunctionWithTypeArguments.errors.txt | 28 +++++----- ...lWithWrongNumberOfTypeArguments.errors.txt | 8 +-- ...torInvocationWithTooFewTypeArgs.errors.txt | 4 +- .../emptyTypeArgumentList.errors.txt | 4 +- .../emptyTypeArgumentListWithNew.errors.txt | 4 +- .../reference/functionCall13.errors.txt | 4 +- .../reference/functionCall16.errors.txt | 4 +- .../reference/functionCall17.errors.txt | 4 +- ...kedInsideItsContainingFunction1.errors.txt | 24 ++++---- .../genericDefaultsErrors.errors.txt | 8 +-- .../genericWithOpenTypeParameters1.errors.txt | 8 +-- ...sWithWrongNumberOfTypeArguments.errors.txt | 8 +-- ...NonGenericTypeWithTypeArguments.errors.txt | 12 ++-- .../reference/iteratorSpreadInCall.errors.txt | 4 +- .../iteratorSpreadInCall10.errors.txt | 4 +- .../iteratorSpreadInCall2.errors.txt | 4 +- .../iteratorSpreadInCall4.errors.txt | 4 +- ...citTypeParameterAndArgumentType.errors.txt | 4 +- .../reference/overloadResolution.errors.txt | 4 +- ...loadResolutionClassConstructors.errors.txt | 12 ++-- .../overloadResolutionConstructors.errors.txt | 4 +- ...loadsAndTypeArgumentArityErrors.errors.txt | 8 +-- .../parserConstructorAmbiguity3.errors.txt | 4 +- .../restParamsWithNonRestParams.errors.txt | 4 +- .../tooManyTypeParameters1.errors.txt | 12 ++-- ...OnFunctionsWithNoTypeParameters.errors.txt | 8 +-- .../reference/typeAssertions.errors.txt | 4 +- .../unionTypeCallSignatures.errors.txt | 4 +- .../unionTypeConstructSignatures.errors.txt | 4 +- ...unctionCallsWithTypeParameters1.errors.txt | 16 +++--- 32 files changed, 144 insertions(+), 144 deletions(-) diff --git a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt index 8c2fdd533f0..d476f1f08e2 100644 --- a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt +++ b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(3,1): error TS2322: Type 'Object' is not assignable to type 'RegExp'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'exec' is missing in type 'Object'. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2557: Expected 0 type arguments, but got 1. tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Type 'Object' is not assignable to type 'Error'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'name' is missing in type 'Object'. @@ -19,10 +19,10 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Ty var a: String = Object.create(""); ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var c: String = Object.create(1); ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var w: Error = new Object(); ~ diff --git a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt index 3c5b03fab50..99fc058d8bd 100644 --- a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt @@ -1,17 +1,17 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2554: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2554: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2554: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2554: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2554: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2554: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2554: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2554: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2554: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2554: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2554: Expected 0 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2554: Expected 0 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2557: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2557: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2557: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2557: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2557: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2557: Expected 0 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2557: Expected 0 type arguments, but got 3. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts (14 errors) ==== @@ -21,26 +21,26 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti function f(x: T, y: U): T { return null; } var r1 = f(1, ''); ~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. var r1b = f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 3. +!!! error TS2557: Expected 2 type arguments, but got 3. var f2 = (x: T, y: U): T => { return null; } var r2 = f2(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. var r2b = f2(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 3. +!!! error TS2557: Expected 2 type arguments, but got 3. var f3: { (x: T, y: U): T; } var r3 = f3(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. var r3b = f3(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 3. +!!! error TS2557: Expected 2 type arguments, but got 3. class C { f(x: T, y: U): T { @@ -49,10 +49,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r4 = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. var r4b = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 3. +!!! error TS2557: Expected 2 type arguments, but got 3. interface I { f(x: T, y: U): T; @@ -60,10 +60,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i: I; var r5 = i.f(1, ''); ~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. var r5b = i.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 3. +!!! error TS2557: Expected 2 type arguments, but got 3. class C2 { f(x: T, y: U): T { @@ -72,10 +72,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r6 = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r6b = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 3. +!!! error TS2557: Expected 0 type arguments, but got 3. interface I2 { f(x: T, y: U): T; @@ -83,7 +83,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i2: I2; var r7 = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r7b = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 3. \ No newline at end of file +!!! error TS2557: Expected 0 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt index 466c6e0828e..72f9908fcee 100644 --- a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt +++ b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2557: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(40,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(43,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,17 +16,17 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun function f(x: number) { return null; } var r = f(1); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var f2 = (x: number) => { return null; } var r2 = f2(1); ~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var f3: { (x: number): any; } var r3 = f3(1); ~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. class C { f(x: number) { @@ -35,7 +35,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r4 = (new C()).f(1); ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. interface I { f(x: number): any; @@ -43,7 +43,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i: I; var r5 = i.f(1); ~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. class C2 { f(x: number) { @@ -52,7 +52,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r6 = (new C2()).f(1); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. interface I2 { f(x: number); @@ -60,7 +60,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i2: I2; var r7 = i2.f(1); ~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var a; var r8 = a(); diff --git a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt index be5d2ed364f..87fe7f62acf 100644 --- a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2554: Expected 2 type arguments, but got 1. -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2554: Expected 2 type arguments, but got 3. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2557: Expected 2 type arguments, but got 3. ==== tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -7,8 +7,8 @@ tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2554: E f(); ~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. f(); f(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 3. \ No newline at end of file +!!! error TS2557: Expected 2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt index 8fec159562c..d36448773bd 100644 --- a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt +++ b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2557: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts (1 errors) ==== @@ -12,5 +12,5 @@ tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS25 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTypeArgumentList.errors.txt b/tests/baselines/reference/emptyTypeArgumentList.errors.txt index eea58f5a4d7..c9d041ba31e 100644 --- a/tests/baselines/reference/emptyTypeArgumentList.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentList.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2554: Expected 1 type arguments, but got 0. +tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2557: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument function foo() { } foo<>(); ~~~~~~~ -!!! error TS2554: Expected 1 type arguments, but got 0. +!!! error TS2557: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt index c60e4221997..88d0981babb 100644 --- a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2554: Expected 1 type arguments, but got 0. +tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2557: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type ar class foo { } new foo<>(); ~~~~~~~~~~~ -!!! error TS2554: Expected 1 type arguments, but got 0. +!!! error TS2557: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall13.errors.txt b/tests/baselines/reference/functionCall13.errors.txt index 3e5ed7655b8..9549ac36648 100644 --- a/tests/baselines/reference/functionCall13.errors.txt +++ b/tests/baselines/reference/functionCall13.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall13.ts(4,1): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/compiler/functionCall13.ts(4,1): error TS2554: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -8,7 +8,7 @@ tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2553: Expected at least 1 arguments, but got 0. +!!! error TS2554: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall16.errors.txt b/tests/baselines/reference/functionCall16.errors.txt index 04b463031f2..d77f2f996db 100644 --- a/tests/baselines/reference/functionCall16.errors.txt +++ b/tests/baselines/reference/functionCall16.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall16.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall16.ts(5,1): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/compiler/functionCall16.ts(5,1): error TS2554: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' foo('foo', 'bar'); foo(); ~~~~~ -!!! error TS2553: Expected at least 1 arguments, but got 0. +!!! error TS2554: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall17.errors.txt b/tests/baselines/reference/functionCall17.errors.txt index 8d1ba39e2b4..77184809b80 100644 --- a/tests/baselines/reference/functionCall17.errors.txt +++ b/tests/baselines/reference/functionCall17.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall17.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall17.ts(4,1): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/compiler/functionCall17.ts(4,1): error TS2554: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall17.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2553: Expected at least 1 arguments, but got 0. +!!! error TS2554: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt index 7092e8ef0ae..74450aba3b5 100644 --- a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt +++ b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt @@ -1,33 +1,33 @@ -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2557: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(3,16): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2557: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(12,17): error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2557: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts (8 errors) ==== function foo(x:T, y:U, f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r4 = f(null); var r11 = f(x); var r21 = f(x); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r31 = f(null); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r41 = f(null); var r12 = f(y); @@ -35,9 +35,9 @@ tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15 !!! error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. var r22 = f(y); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r32 = f(null); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r42 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/genericDefaultsErrors.errors.txt b/tests/baselines/reference/genericDefaultsErrors.errors.txt index 8ac07d68e95..9067eb5d89d 100644 --- a/tests/baselines/reference/genericDefaultsErrors.errors.txt +++ b/tests/baselines/reference/genericDefaultsErrors.errors.txt @@ -3,8 +3,8 @@ tests/cases/compiler/genericDefaultsErrors.ts(4,59): error TS2344: Type 'T' does Type 'string' is not assignable to type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(5,44): error TS2344: Type 'T' does not satisfy the constraint 'number'. tests/cases/compiler/genericDefaultsErrors.ts(6,39): error TS2344: Type 'number' does not satisfy the constraint 'T'. -tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2554: Expected 2-3 type arguments, but got 1. -tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2554: Expected 2-3 type arguments, but got 4. +tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2557: Expected 2-3 type arguments, but got 1. +tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2557: Expected 2-3 type arguments, but got 4. tests/cases/compiler/genericDefaultsErrors.ts(17,13): error TS2345: Argument of type '"a"' is not assignable to parameter of type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(19,11): error TS2428: All declarations of 'i00' must have identical type parameters. tests/cases/compiler/genericDefaultsErrors.ts(20,11): error TS2428: All declarations of 'i00' must have identical type parameters. @@ -44,12 +44,12 @@ tests/cases/compiler/genericDefaultsErrors.ts(38,20): error TS4033: Property 'x' f11(); // ok f11<1>(); // error ~~~~~~~~ -!!! error TS2554: Expected 2-3 type arguments, but got 1. +!!! error TS2557: Expected 2-3 type arguments, but got 1. f11<1, 2>(); // ok f11<1, 2, 3>(); // ok f11<1, 2, 3, 4>(); // error ~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2-3 type arguments, but got 4. +!!! error TS2557: Expected 2-3 type arguments, but got 4. declare function f12(a?: U): void; f12(); // ok diff --git a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt index a63ef43848c..12fff1ff40e 100644 --- a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt +++ b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(7,40): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2557: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericWithOpenTypeParameters1.ts (3 errors) ==== @@ -15,9 +15,9 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2554: Expe !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var f2 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var f3 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var f4 = (x: B) => { return x.foo(1); } // no error \ No newline at end of file diff --git a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt index 9c5d62d2419..77de65db461 100644 --- a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2554: Expected 1 type arguments, but got 2. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2557: Expected 1 type arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2557: Expected 2 type arguments, but got 1. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -12,7 +12,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri var c = new C(); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 type arguments, but got 2. +!!! error TS2557: Expected 1 type arguments, but got 2. class D { x: T @@ -22,4 +22,4 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri // BUG 794238 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. \ No newline at end of file +!!! error TS2557: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt index 4d726c4c8ca..5ce7cede0d0 100644 --- a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2557: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2557: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2557: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(18,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,21 +16,21 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGen var c = new C(); ~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. function Foo(): void { } var r = new Foo(); ~~~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var f: { (): void }; var r2 = new f(); ~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var a: any; // BUG 790977 diff --git a/tests/baselines/reference/iteratorSpreadInCall.errors.txt b/tests/baselines/reference/iteratorSpreadInCall.errors.txt index 7e5576baa3a..d44fa5c3e2e 100644 --- a/tests/baselines/reference/iteratorSpreadInCall.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2553: Expected 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2555: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2553: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2555: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt index d302644762a..8bdefd6732d 100644 --- a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2553: Expected 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2555: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2553 foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2555: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt index 3647aa0fd77..d36e95df24c 100644 --- a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2553: Expected 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2555: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2553: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2555: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt index 9d444d2269a..81fe5c9a271 100644 --- a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2553: Expected at least 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2556: Expected at least 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2553: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected at least 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2556: Expected at least 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt index 9107b2b162b..7c4c287f179 100644 --- a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt +++ b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(10,30): error TS2345: Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2554: Expected 2 type arguments, but got 1. +tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2557: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts (2 errors) ==== @@ -21,5 +21,5 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): e !!! error TS2345: Type 'string' is not assignable to type 'number'. var r7b = map([1, ""], (x) => x.toString()); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 2 type arguments, but got 1. +!!! error TS2557: Expected 2 type arguments, but got 1. var r8 = map([1, ""], (x) => x.toString()); \ No newline at end of file diff --git a/tests/baselines/reference/overloadResolution.errors.txt b/tests/baselines/reference/overloadResolution.errors.txt index f122b74d55e..a924826a6a0 100644 --- a/tests/baselines/reference/overloadResolution.errors.txt +++ b/tests/baselines/reference/overloadResolution.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(27,5): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(41,11): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2554: Expected 1-3 type arguments, but got 4. +tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2557: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(70,21): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(71,21): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(81,5): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -79,7 +79,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(91,22): // Generic overloads with differing arity called with type argument count that doesn't match any overload fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1-3 type arguments, but got 4. +!!! error TS2557: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints function fn4(n: T, m: U); diff --git a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt index 998fa1fa96d..9306fa8e1a2 100644 --- a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2554: Expected 3 type arguments, but got 1. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2554: Expected 3 type arguments, but got 2. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2554: Expected 3 type arguments, but got 4. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2557: Expected 3 type arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2557: Expected 3 type arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2557: Expected 3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(73,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(74,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(75,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. @@ -78,16 +78,16 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstru // Generic overloads with differing arity called with type arguments matching each overload type parameter count new fn3(4); // Error ~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 3 type arguments, but got 1. +!!! error TS2557: Expected 3 type arguments, but got 1. new fn3('', '', ''); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 3 type arguments, but got 2. +!!! error TS2557: Expected 3 type arguments, but got 2. new fn3('', '', 3); // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 3 type arguments, but got 4. +!!! error TS2557: Expected 3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints class fn4 { diff --git a/tests/baselines/reference/overloadResolutionConstructors.errors.txt b/tests/baselines/reference/overloadResolutionConstructors.errors.txt index c8741795245..f0008553f2e 100644 --- a/tests/baselines/reference/overloadResolutionConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionConstructors.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(43,15): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2554: Expected 1-3 type arguments, but got 4. +tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2557: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(77,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(78,25): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(88,9): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -83,7 +83,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1-3 type arguments, but got 4. +!!! error TS2557: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints interface fn4 { diff --git a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt index 661def113d4..d79421264d4 100644 --- a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt +++ b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2554: Expected 0-2 type arguments, but got 3. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2557: Expected 0-2 type arguments, but got 3. tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2554: Expected 0-2 type arguments, but got 3. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2557: Expected 0-2 type arguments, but got 3. ==== tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts (3 errors) ==== @@ -10,9 +10,9 @@ tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2554: Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0-2 type arguments, but got 3. +!!! error TS2557: Expected 0-2 type arguments, but got 3. new Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0-2 type arguments, but got 3. \ No newline at end of file +!!! error TS2557: Expected 0-2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt index b34235df7fb..5ac1a1003ba 100644 --- a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt +++ b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2557: Expected 0 type arguments, but got 1. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,10): error TS2304: Cannot find name 'A'. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,12): error TS1005: '(' expected. @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts (3 errors) ==== new Date ~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. ~ !!! error TS2304: Cannot find name 'A'. diff --git a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt index 5f22e34383a..3568d92931c 100644 --- a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt +++ b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2554: Expected at least 1 arguments, but got 0. ==== tests/cases/compiler/restParamsWithNonRestParams.ts (1 errors) ==== @@ -7,6 +7,6 @@ tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2553: Expected function foo2(a:string, ...b:number[]){} foo2(); // should be an error ~~~~~~ -!!! error TS2553: Expected at least 1 arguments, but got 0. +!!! error TS2554: Expected at least 1 arguments, but got 0. function foo3(a?:string, ...b:number[]){} foo3(); // error but shouldn't be \ No newline at end of file diff --git a/tests/baselines/reference/tooManyTypeParameters1.errors.txt b/tests/baselines/reference/tooManyTypeParameters1.errors.txt index 8ff1f031d9b..9bbb6665bc0 100644 --- a/tests/baselines/reference/tooManyTypeParameters1.errors.txt +++ b/tests/baselines/reference/tooManyTypeParameters1.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2554: Expected 1 type arguments, but got 2. -tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2554: Expected 1 type arguments, but got 2. -tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2554: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2557: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2557: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2557: Expected 1 type arguments, but got 2. tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type 'I' requires 1 type argument(s). @@ -8,17 +8,17 @@ tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type function f() { } f(); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 type arguments, but got 2. +!!! error TS2557: Expected 1 type arguments, but got 2. var x = () => {}; x(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 type arguments, but got 2. +!!! error TS2557: Expected 1 type arguments, but got 2. class C {} var c = new C(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 type arguments, but got 2. +!!! error TS2557: Expected 1 type arguments, but got 2. interface I {} var i: I; diff --git a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt index df122c8d591..5f52dea520a 100644 --- a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt +++ b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt @@ -1,19 +1,19 @@ -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2557: Expected 0 type arguments, but got 1. tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(3,15): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2557: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts (3 errors) ==== function foo(f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var r4 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index 28b72d37767..3787e2e67d4 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2557: Expected 0 type arguments, but got 1. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(31,12): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeBase'. Property 'p' is missing in type 'SomeOther'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(35,15): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeDerived'. @@ -30,7 +30,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err fn1(fn2(4)); // Error ~~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var a: any; var s: string; diff --git a/tests/baselines/reference/unionTypeCallSignatures.errors.txt b/tests/baselines/reference/unionTypeCallSignatures.errors.txt index 4bad49206ee..7e0b99d92a5 100644 --- a/tests/baselines/reference/unionTypeCallSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures.errors.txt @@ -19,7 +19,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(47,12): error TS2 tests/cases/conformance/types/union/unionTypeCallSignatures.ts(48,12): error TS2553: Expected 1 arguments, but got 2. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(49,12): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(55,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2554: Expected at least 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(59,12): error TS2553: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(61,12): error TS2553: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(62,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. @@ -131,7 +131,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected at least 1 arguments, but got 0. +!!! error TS2554: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { (a: string, ...b: number[]): string; } | { (a: string, b: number): number }; strOrNum = unionWithRestParameter2('hello'); // error no call signature diff --git a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt index 18f08209048..bcfa70b925a 100644 --- a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt @@ -19,7 +19,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(47,12): erro tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(48,12): error TS2553: Expected 1 arguments, but got 2. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(49,12): error TS2553: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(55,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2553: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2554: Expected at least 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(59,12): error TS2553: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(61,12): error TS2553: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(62,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. @@ -130,7 +130,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected at least 1 arguments, but got 0. +!!! error TS2554: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { new (a: string, ...b: number[]): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithRestParameter2('hello'); // error no call signature diff --git a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt index e5f4dd630ab..ee51408b19f 100644 --- a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt +++ b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt @@ -1,13 +1,13 @@ -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2557: Expected 0 type arguments, but got 1. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(5,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(8,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(10,7): error TS2420: Class 'C' incorrectly implements interface 'Function'. Property 'apply' is missing in type 'C'. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(18,10): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'C' has no compatible call signatures. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(22,10): error TS2347: Untyped function calls may not accept type arguments. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2554: Expected 0 type arguments, but got 1. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2554: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2557: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts (9 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var x = function () { return; }; var r1 = x(); ~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. var y: any = x; var r2 = y(); ~~~~~~~~~~~ @@ -53,7 +53,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var z: I; var r6 = z(1); // error ~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. interface callable2 { (a: T): T; @@ -62,7 +62,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c4: callable2; c4(1); ~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. interface callable3 { (a: T): T; } @@ -70,6 +70,6 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c5: callable3; c5(1); // error ~~~~~~~~~~~~~ -!!! error TS2554: Expected 0 type arguments, but got 1. +!!! error TS2557: Expected 0 type arguments, but got 1. \ No newline at end of file From ed1a6c10e2281d8c51b53d60e6957a03289d4a73 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 16 May 2017 09:12:32 -0700 Subject: [PATCH 216/282] Address CR feedback + defer creation of visited map --- src/compiler/checker.ts | 53 ++++++++++++++++------------------------- 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 26cdab1e599..602125091ab 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10096,31 +10096,12 @@ namespace ts { inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } - function getSymbolForInference(type: Type) { - // Exclude the static side of classes since it shares its symbol with the instance side which leads - // to false positives. - return type.flags & TypeFlags.Object && !(getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class) ? type.symbol : undefined; - } - function inferTypes(typeVariables: TypeVariable[], typeInferences: TypeInferences[], originalSource: Type, originalTarget: Type) { - let stack: Type[]; - let depth = 0; + let symbolStack: Symbol[]; + let visited: Map; let inferiority = 0; - const visited = createMap(); inferFromTypes(originalSource, originalTarget); - function isInstantiationInProcess(type: Type) { - const symbol = getSymbolForInference(type); - if (symbol) { - for (let i = 0; i < depth; i++) { - const t = stack[i]; - if (getSymbolForInference(t) === symbol) { - return true; - } - } - } - } - function inferFromTypes(source: Type, target: Type) { if (!couldContainTypeVariables(target)) { return; @@ -10248,21 +10229,29 @@ namespace ts { else { source = getApparentType(source); if (source.flags & TypeFlags.Object) { + const key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (visited || (visited = createMap())).set(key, true); // If we are already processing another target type with the same associated symbol (such as // an instantiation of the same generic type), we do not explore this target as it would yield - // no further inferences. - if (isInstantiationInProcess(target)) { - return; + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + const isNonConstructorObject = target.flags & TypeFlags.Object && + !(getObjectFlags(target) & ObjectFlags.Anonymous && target.symbol && target.symbol.flags & SymbolFlags.Class); + const symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); } - const key = source.id + "," + target.id; - if (visited.get(key)) { - return; + else { + inferFromObjectTypes(source, target); } - visited.set(key, true); - (stack || (stack = []))[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } From ffa21fe271d09eb964dad6715c272965294be981 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 16 May 2017 09:38:26 -0700 Subject: [PATCH 217/282] getDeclarationOfKind: Improve type safety --- src/compiler/checker.ts | 28 ++++++++++++++-------------- src/compiler/utilities.ts | 4 ++-- src/services/findAllReferences.ts | 4 ++-- src/services/symbolDisplay.ts | 4 ++-- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a2a31e3a197..5c37ff2c6ce 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2731,7 +2731,7 @@ namespace ts { } function symbolToParameterDeclaration(parameterSymbol: Symbol): ParameterDeclaration { - const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); + const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); const parameterType = getTypeOfSymbol(parameterSymbol); const parameterTypeNode = typeToTypeNodeHelper(parameterType); // TODO(aozgaa): In the future, check initializer accessibility. @@ -4100,7 +4100,7 @@ namespace ts { const func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present if (func.kind === SyntaxKind.SetAccessor && !hasDynamicName(func)) { - const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { const getterSignature = getSignatureFromDeclaration(getter); const thisParameter = getAccessorThisParameter(func as AccessorDeclaration); @@ -4389,8 +4389,8 @@ namespace ts { function getTypeOfAccessors(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.type) { - const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); if (getter && getter.flags & NodeFlags.JavaScriptFile) { const jsDocType = getTypeForDeclarationFromJSDocComment(getter); @@ -4439,7 +4439,7 @@ namespace ts { if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -4916,7 +4916,7 @@ namespace ts { return unknownType; } - let declaration: JSDocTypedefTag | TypeAliasDeclaration = getDeclarationOfKind(symbol, SyntaxKind.JSDocTypedefTag); + let declaration: JSDocTypedefTag | TypeAliasDeclaration = getDeclarationOfKind(symbol, SyntaxKind.JSDocTypedefTag); let type: Type; if (declaration) { if (declaration.jsDocTypeLiteral) { @@ -4927,7 +4927,7 @@ namespace ts { } } else { - declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); + declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); type = getTypeFromTypeNode(declaration.type); } @@ -6220,7 +6220,7 @@ namespace ts { !hasDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { const otherKind = declaration.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - const other = getDeclarationOfKind(declaration.symbol, otherKind); + const other = getDeclarationOfKind(declaration.symbol, otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } @@ -6263,7 +6263,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. if (declaration.kind === SyntaxKind.GetAccessor && !hasDynamicName(declaration)) { - const setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); + const setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); return getAnnotatedAccessorType(setter); } @@ -6476,7 +6476,7 @@ namespace ts { } function getConstraintDeclaration(type: TypeParameter) { - return (getDeclarationOfKind(type.symbol, SyntaxKind.TypeParameter)).constraint; + return getDeclarationOfKind(type.symbol, SyntaxKind.TypeParameter).constraint; } function getConstraintFromTypeParameter(typeParameter: TypeParameter): Type { @@ -12567,7 +12567,7 @@ namespace ts { // corresponding set accessor has a type annotation, return statements in the function are contextually typed if (functionDecl.type || functionDecl.kind === SyntaxKind.Constructor || - functionDecl.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(functionDecl.symbol, SyntaxKind.SetAccessor))) { + functionDecl.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(functionDecl.symbol, SyntaxKind.SetAccessor))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } @@ -18110,7 +18110,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. const otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - const otherAccessor = getDeclarationOfKind(node.symbol, otherKind); + const otherAccessor = getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if ((getModifierFlags(node) & ModifierFlags.AccessibilityModifier) !== (getModifierFlags(otherAccessor) & ModifierFlags.AccessibilityModifier)) { error(node.name, Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); @@ -20242,7 +20242,7 @@ namespace ts { } function isGetAccessorWithAnnotatedSetAccessor(node: FunctionLikeDeclaration) { - return !!(node.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(node.symbol, SyntaxKind.SetAccessor))); + return !!(node.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(node.symbol, SyntaxKind.SetAccessor))); } function isUnwrappedReturnTypeVoidOrAny(func: FunctionLikeDeclaration, returnType: Type): boolean { @@ -20930,7 +20930,7 @@ namespace ts { checkTypeParameterListsIdentical(symbol); // Only check this symbol once - const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); if (node === firstInterfaceDecl) { const type = getDeclaredTypeOfSymbol(symbol); const typeWithThis = getTypeWithThisArgument(type); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5046b44d094..98b22605ad7 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -11,12 +11,12 @@ namespace ts { isTypeReferenceDirective?: boolean; } - export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { + export function getDeclarationOfKind(symbol: Symbol, kind: T["kind"]): T { const declarations = symbol.declarations; if (declarations) { for (const declaration of declarations) { if (declaration.kind === kind) { - return declaration; + return declaration as T; } } } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 395c282f6d5..d9deaef9e56 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -550,7 +550,7 @@ namespace ts.FindAllReferences.Core { } function isObjectBindingPatternElementWithoutPropertyName(symbol: Symbol): boolean { - const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); + const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); return bindingElement && bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern && !bindingElement.propertyName; @@ -558,7 +558,7 @@ namespace ts.FindAllReferences.Core { function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined { if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); + const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && checker.getPropertyOfType(typeOfPattern, (bindingElement.name).text); } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 4268a52c419..5e9d115b33e 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -275,7 +275,7 @@ namespace ts.SymbolDisplay { } if (symbolFlags & SymbolFlags.Module) { addNewLineIfDisplayPartsExist(); - const declaration = getDeclarationOfKind(symbol, SyntaxKind.ModuleDeclaration); + const declaration = getDeclarationOfKind(symbol, SyntaxKind.ModuleDeclaration); const isNamespace = declaration && declaration.name && declaration.name.kind === SyntaxKind.Identifier; displayParts.push(keywordPart(isNamespace ? SyntaxKind.NamespaceKeyword : SyntaxKind.ModuleKeyword)); displayParts.push(spacePart()); @@ -296,7 +296,7 @@ namespace ts.SymbolDisplay { } else { // Method/function type parameter - let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter); + let declaration: Node = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter); Debug.assert(declaration !== undefined); declaration = declaration.parent; From badfcbfb43f594710020481662fa2ae680ddfecd Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 16 May 2017 09:45:01 -0700 Subject: [PATCH 218/282] findAncestor: Add generic overload for use with type predicates --- src/compiler/checker.ts | 4 ++-- src/compiler/core.ts | 2 ++ src/compiler/utilities.ts | 4 ++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7a22c841450..5b816656183 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1300,7 +1300,7 @@ namespace ts { return node; } - return findAncestor(node, n => n.kind === SyntaxKind.ImportDeclaration) as ImportDeclaration; + return findAncestor(node, isImportDeclaration); } } @@ -22638,7 +22638,7 @@ namespace ts { const symbolIsUmdExport = symbolFile !== referenceFile; return symbolIsUmdExport ? undefined : symbolFile; } - return findAncestor(node.parent, n => isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) as ModuleDeclaration | EnumDeclaration; + return findAncestor(node.parent, (n): n is ModuleDeclaration | EnumDeclaration => isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol); } } } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 5e4afce98c8..60553fdab01 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -230,6 +230,8 @@ namespace ts { * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" * At that point findAncestor returns undefined. */ + export function findAncestor(node: Node, callback: (element: Node) => element is T): T | undefined; + export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node | undefined; export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node { while (node) { const result = callback(node); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5046b44d094..43a144f9045 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4010,6 +4010,10 @@ namespace ts { return node.kind === SyntaxKind.ImportEqualsDeclaration; } + export function isImportDeclaration(node: Node): node is ImportDeclaration { + return node.kind === SyntaxKind.ImportDeclaration; + } + export function isImportClause(node: Node): node is ImportClause { return node.kind === SyntaxKind.ImportClause; } From 353d9e231034e86bd3dee145ec7fb408ca5f9e0a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 16 May 2017 09:48:23 -0700 Subject: [PATCH 219/282] Clean up original errors The old "supplied parameters do not match any call signature" was either inaccurate, redundant or vague. The previous commits fix the vagueness problem. This commit fixes the inaccuracy and redundancy. 1. When there are NO candidates, the error should say so. (This only happens once in our tests, when calling `super()` with a base class of type `any` in a JS file.) 2. When the call is to a decorator, `resolveCall` already receives a specific fallback error message from the decorator handling code. Adding "supplied parameters do not match ..." is not helpful. I also cleaned up the new code a bit after I noticed that all the error creation functions take `string | number`, so I didn't need calls to `toString` in my code. --- src/compiler/checker.ts | 31 +++++++++------------------- src/compiler/diagnosticMessages.json | 2 +- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 73147bb99bb..62c89346202 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15208,7 +15208,7 @@ namespace ts { } } - function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], headMessage?: DiagnosticMessage): Signature { + function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], fallbackError?: DiagnosticMessage): Signature { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); @@ -15243,7 +15243,7 @@ namespace ts { // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } @@ -15351,7 +15351,7 @@ namespace ts { else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { const typeArguments = (node).typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -15362,8 +15362,8 @@ namespace ts { Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, (node).tagName || (node).expression || (node).tag, diagnosticChainHead); @@ -15376,8 +15376,8 @@ namespace ts { min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, length(sig.typeParameters)); } - const paramMessage = max > min ? `${min}-${max}` : min.toString(); - reportError(Diagnostics.Expected_0_type_arguments_but_got_1, paramMessage, typeArguments.length.toString()); + const paramCount = min < max ? `${min}-${max}` : min; + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); } else if (args) { let min = Number.POSITIVE_INFINITY; @@ -15386,7 +15386,6 @@ namespace ts { min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } - /////////// const hasRestParameter = some(signatures, sig => sig.hasRestParameter); const hasSpreadArgument = getSpreadArgumentIndex(args) > -1; const paramCount = hasRestParameter ? min : @@ -15397,10 +15396,10 @@ namespace ts { hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : hasSpreadArgument ? Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : Diagnostics.Expected_0_arguments_but_got_1; - reportError(error, paramCount.toString(), argCount.toString()); + diagnostics.add(createDiagnosticForNode(node, error, paramCount, argCount)); } - else { - reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (fallbackError) { + diagnostics.add(createDiagnosticForNode(node, fallbackError)); } // No signature was applicable. We have already reported the errors for the invalid signature. @@ -15421,16 +15420,6 @@ namespace ts { return resolveErrorCall(node); - function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void { - let errorInfo: DiagnosticMessageChain; - errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = chainDiagnosticMessages(errorInfo, headMessage); - } - - diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } - function chooseOverload(candidates: Signature[], relation: Map, signatureHelpTrailingComma = false) { for (const originalCandidate of candidates) { if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 0f4d373c05b..14aea1bcd78 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1067,7 +1067,7 @@ "category": "Error", "code": 2345 }, - "Supplied parameters do not match any signature of call target.": { + "Call target does not contain any signatures.": { "category": "Error", "code": 2346 }, From 995f1a6757f3312c176e7d3ffa21263d03787108 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 16 May 2017 09:53:38 -0700 Subject: [PATCH 220/282] Update baselines --- ...checkIndexConstraintOfJavascriptClassExpression.errors.txt | 4 ++-- tests/baselines/reference/decoratorOnClass8.errors.txt | 2 -- tests/baselines/reference/decoratorOnClassMethod6.errors.txt | 2 -- tests/baselines/reference/decoratorOnClassMethod8.errors.txt | 2 -- .../baselines/reference/decoratorOnClassProperty11.errors.txt | 2 -- .../baselines/reference/decoratorOnClassProperty6.errors.txt | 2 -- .../baselines/reference/decoratorOnClassProperty7.errors.txt | 2 -- 7 files changed, 2 insertions(+), 14 deletions(-) diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt index d90e6d506ff..b409185a114 100644 --- a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/weird.js(1,1): error TS2304: Cannot find name 'someFunction'. tests/cases/compiler/weird.js(1,23): error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. -tests/cases/compiler/weird.js(6,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/weird.js(6,13): error TS2346: Call target does not contain any signatures. tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly has an 'any' type. @@ -16,7 +16,7 @@ tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly constructor() { super(); ~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2346: Call target does not contain any signatures. this.foo = "bar"; } _render(error) { diff --git a/tests/baselines/reference/decoratorOnClass8.errors.txt b/tests/baselines/reference/decoratorOnClass8.errors.txt index f9ca7fca210..4c13520364b 100644 --- a/tests/baselines/reference/decoratorOnClass8.errors.txt +++ b/tests/baselines/reference/decoratorOnClass8.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1238: Unable to resolve signature of class decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/decoratorOnClass8.ts (1 errors) ==== @@ -8,6 +7,5 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1238 @dec() ~~~~~~ !!! error TS1238: Unable to resolve signature of class decorator when called as an expression. -!!! error TS1238: Supplied parameters do not match any signature of call target. class C { } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt index c8ee66717ef..530e86117ee 100644 --- a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1241: Unable to resolve signature of method decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): @dec ["method"]() {} ~~~~ !!! error TS1241: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1241: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt index f522dc01df9..3ada30296b6 100644 --- a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1241: Unable to resolve signature of method decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): @dec method() {} ~~~~ !!! error TS1241: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1241: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt index 6ff700564e8..2a72fefa53e 100644 --- a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts( @dec prop; ~~~~ !!! error TS1240: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt index dbb104e8cd3..b40a81fe1c9 100644 --- a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4 @dec prop; ~~~~ !!! error TS1240: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt index 41396acd17e..47f8ad5ae8c 100644 --- a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. - Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts (1 errors) ==== @@ -9,5 +8,4 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4 @dec prop; ~~~~ !!! error TS1240: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file From ea42644c8f5d50633237438cc37637c8b4e4e4e1 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 16 May 2017 10:25:46 -0700 Subject: [PATCH 221/282] Replace unnecessary `let` with two `const`s --- src/services/symbolDisplay.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 5e9d115b33e..71dc7b78133 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -296,9 +296,9 @@ namespace ts.SymbolDisplay { } else { // Method/function type parameter - let declaration: Node = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter); - Debug.assert(declaration !== undefined); - declaration = declaration.parent; + const decl = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter); + Debug.assert(decl !== undefined); + const declaration = decl.parent; if (declaration) { if (isFunctionLikeKind(declaration.kind)) { From 56d04429b31e2f440589c026de64e7722b471e1c Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Tue, 16 May 2017 11:30:30 -0700 Subject: [PATCH 222/282] Add target and lib references for tsc-instrumented I think they were previously provided implicitly. --- Gulpfile.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Gulpfile.ts b/Gulpfile.ts index 32fbf2c43e0..03046789fe1 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -935,7 +935,7 @@ gulp.task(loggedIOJsPath, /*help*/ false, [], (done) => { const temp = path.join(builtLocalDirectory, "temp"); mkdirP(temp, (err) => { if (err) { console.error(err); done(err); process.exit(1); } - exec(host, [LKGCompiler, "--types --outdir", temp, loggedIOpath], () => { + exec(host, [LKGCompiler, "--types", "--target es5", "--lib es5", "--outdir", temp, loggedIOpath], () => { fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath); del(temp).then(() => done(), done); }, done); @@ -946,7 +946,13 @@ const instrumenterPath = path.join(harnessDirectory, "instrumenter.ts"); const instrumenterJsPath = path.join(builtLocalDirectory, "instrumenter.js"); gulp.task(instrumenterJsPath, /*help*/ false, [servicesFile], () => { const settings: tsc.Settings = getCompilerSettings({ - outFile: instrumenterJsPath + outFile: instrumenterJsPath, + target: "es5", + lib: [ + "es6", + "dom", + "scripthost" + ] }, /*useBuiltCompiler*/ true); return gulp.src(instrumenterPath) .pipe(newer(instrumenterJsPath)) From 5fb77a09011facdac31bd9cf5fb84f734026adac Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Tue, 16 May 2017 23:13:58 +0200 Subject: [PATCH 223/282] Update return types of APIs (#15887) * Update types.ts * Update types in parser.ts and scanner.ts --- src/compiler/parser.ts | 8 ++++---- src/compiler/scanner.ts | 13 +++++++------ src/compiler/types.ts | 30 +++++++++++++++--------------- 3 files changed, 26 insertions(+), 25 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index dd189784a17..2d9806bcbf4 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -23,19 +23,19 @@ namespace ts { } } - function visitNode(cbNode: (node: Node) => T, node: Node): T { + function visitNode(cbNode: (node: Node) => T, node: Node): T | undefined { if (node) { return cbNode(node); } } - function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes: Node[]) { + function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes: Node[]): T | undefined { if (nodes) { return cbNodes(nodes); } } - function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { + function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]): T | undefined { if (nodes) { for (const node of nodes) { const result = cbNode(node); @@ -50,7 +50,7 @@ namespace ts { // stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, // 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. - export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T { + export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined { if (!node) { return; } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 659c2f416ab..d27bbf879fe 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -712,11 +712,11 @@ namespace ts { return accumulator; } - export function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) { + export function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined { return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); } - export function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) { + export function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined { return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); } @@ -746,10 +746,11 @@ namespace ts { } /** Optionally, get the shebang */ - export function getShebang(text: string): string { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + export function getShebang(text: string): string | undefined { + const match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 67d80a92ce2..955bb0622dd 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2527,11 +2527,11 @@ namespace ts { indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -2542,15 +2542,15 @@ namespace ts { getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; /* @internal */ getMergedSymbol(symbol: Symbol): Symbol; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; @@ -2560,7 +2560,7 @@ namespace ts { /** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */ /* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -2568,10 +2568,10 @@ namespace ts { tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; - getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string; - /* @internal */ getBaseConstraintOfType(type: Type): Type; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; + /* @internal */ getBaseConstraintOfType(type: Type): Type | undefined; - /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol; + /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined; // Should not be called directly. Should only be accessed through the Program instance. /* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -2753,7 +2753,7 @@ namespace ts { getNodeCheckFlags(node: Node): NodeCheckFlags; isDeclarationVisible(node: Declaration): boolean; collectLinkedAliases(node: Identifier): Node[]; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isRequiredInitializedParameter(node: ParameterDeclaration): boolean; writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; @@ -3135,7 +3135,7 @@ namespace ts { */ export interface TypeReference extends ObjectType { target: GenericType; // Type reference target - typeArguments: Type[]; // Type reference type arguments (undefined if none) + typeArguments?: Type[]; // Type reference type arguments (undefined if none) } // Generic class and interface types @@ -3265,7 +3265,7 @@ namespace ts { export interface Signature { declaration: SignatureDeclaration; // Originating declaration - typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) + typeParameters?: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters /* @internal */ thisParameter?: Symbol; // symbol of this-type parameter From 0defde71850fe75b4ee3ef7e5386fd1d4d374fc6 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 16 May 2017 15:04:33 -0700 Subject: [PATCH 224/282] Services utilities: Combine `isInsideComment` with `isInComment` --- src/services/completions.ts | 2 +- src/services/services.ts | 4 +- src/services/utilities.ts | 84 ++++++++++++------------------------- 3 files changed, 30 insertions(+), 60 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index 5bc2a268617..d80eaa9a7ed 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -359,7 +359,7 @@ namespace ts.Completions { start = timestamp(); // Completion not allowed inside comments, bail out if this is the case - const insideComment = isInsideComment(sourceFile, currentToken, position); + const insideComment = isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (timestamp() - start)); if (insideComment) { diff --git a/src/services/services.ts b/src/services/services.ts index 1b4678b5dbc..d35f1e7b8a5 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1853,8 +1853,8 @@ namespace ts { // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - const token = getTokenAtPosition(sourceFile, matchPosition); - if (!isInsideComment(sourceFile, token, matchPosition)) { + + if (!isInComment(sourceFile, matchPosition)) { continue; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 4ae9204f7ed..8a9976e00bb 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -256,37 +256,6 @@ namespace ts { getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } - /** Returns true if the position is within a comment */ - export function isInsideComment(sourceFile: SourceFile, token: Node, position: number): boolean { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - - function isInsideCommentRange(comments: CommentRange[]): boolean { - return forEach(comments, comment => { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - const text = sourceFile.text; - const width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === CharacterCodes.slash) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === CharacterCodes.slash && - text.charCodeAt(comment.end - 2) === CharacterCodes.asterisk); - } - } - return false; - }); - } - } - export function getContainerNode(node: Node): Declaration { while (true) { node = node.parent; @@ -834,10 +803,6 @@ namespace ts { return false; } - export function isInComment(sourceFile: SourceFile, position: number) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - /** * returns true if the position is in between the open and close elements of an JSX expression. */ @@ -883,15 +848,26 @@ namespace ts { } /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - export function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean { - const token = getTokenAtPosition(sourceFile, position); + export function isInComment(sourceFile: SourceFile, position: number, tokenAtPosition = getTokenAtPosition(sourceFile, position), predicate?: (c: CommentRange) => boolean): boolean { + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); - if (token && position <= token.getStart(sourceFile)) { - const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); + function isInCommentRange(commentRanges: CommentRange[]): boolean { + return forEach(commentRanges, c => isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c))); + } + } + function isPositionInCommentRange({ pos, end, kind }: ts.CommentRange, position: number, text: string): boolean { + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -902,15 +878,13 @@ namespace ts { // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - forEach(commentRanges, c => c.pos < position && - (c.kind === SyntaxKind.SingleLineCommentTrivia ? position <= c.end : position < c.end) && - predicate(c)) : - forEach(commentRanges, c => c.pos < position && - (c.kind === SyntaxKind.SingleLineCommentTrivia ? position <= c.end : position < c.end)); + return kind === SyntaxKind.SingleLineCommentTrivia || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === CharacterCodes.slash && text.charCodeAt(end - 2) === CharacterCodes.asterisk); + } + else { + return false; } - - return false; } export function hasDocComment(sourceFile: SourceFile, position: number) { @@ -1093,21 +1067,17 @@ namespace ts { } export function isInReferenceComment(sourceFile: SourceFile, position: number): boolean { - return isInCommentHelper(sourceFile, position, isReferenceComment); - - function isReferenceComment(c: CommentRange): boolean { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, c => { const commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } export function isInNonReferenceComment(sourceFile: SourceFile, position: number): boolean { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - - function isNonReferenceComment(c: CommentRange): boolean { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, c => { const commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } export function createTextSpanFromNode(node: Node, sourceFile?: SourceFile): TextSpan { From 0820f692705e4b1118b0c9a8f57783073f80f8e6 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 16 May 2017 15:28:32 -0700 Subject: [PATCH 225/282] respond to comments --- src/compiler/checker.ts | 48 +++++++++++++++++++-------------------- src/compiler/emitter.ts | 2 +- src/compiler/factory.ts | 15 ++++++------ src/compiler/types.ts | 6 ++--- src/compiler/utilities.ts | 10 ++++---- src/compiler/visitor.ts | 2 -- 6 files changed, 40 insertions(+), 43 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0f2e5e9e0ff..e426a7bdbaf 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2279,7 +2279,7 @@ namespace ts { } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.ignoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName); + const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName); Debug.assert(typeNode !== undefined, "should always get typenode?"); const options = { removeComments: true }; const writer = createTextWriter(""); @@ -2361,7 +2361,7 @@ namespace ts { function typeToTypeNodeHelper(type: Type, context: NodeBuilderContext): TypeNode { const inTypeAlias = context.flags & NodeBuilderFlags.InTypeAlias; - context.flags &= ~(NodeBuilderFlags.InTypeAlias); + context.flags &= ~NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; @@ -2419,7 +2419,7 @@ namespace ts { return createKeywordTypeNode(SyntaxKind.ObjectKeyword); } if (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType) { - if (context.flags & NodeBuilderFlags.inObjectTypeLiteral) { + if (context.flags & NodeBuilderFlags.InObjectTypeLiteral) { if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } @@ -2441,12 +2441,12 @@ namespace ts { if (!inTypeAlias && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { const name = symbolToTypeReferenceName(type.aliasSymbol); - const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments, context); + const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return createTypeReferenceNode(name, typeArgumentNodes); } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; - const typeNodes = types && mapToTypeNodeArray(types, context); + const typeNodes = mapToTypeNodes(types, context); if (typeNodes && typeNodes.length > 0) { const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); return unionOrIntersectionTypeNode; @@ -2567,7 +2567,7 @@ namespace ts { } const savedFlags = context.flags; - context.flags |= NodeBuilderFlags.inObjectTypeLiteral; + context.flags |= NodeBuilderFlags.InObjectTypeLiteral; const members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; const typeLiteralNode = createTypeLiteralNode(members); @@ -2598,8 +2598,7 @@ namespace ts { } else if (type.target.objectFlags & ObjectFlags.Tuple) { if (typeArguments.length > 0) { - const slice = typeArguments.slice(0, getTypeReferenceArity(type)); - const tupleConstituentNodes = slice && mapToTypeNodeArray(slice, context); + const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return createTupleTypeNode(tupleConstituentNodes); } @@ -2625,8 +2624,8 @@ namespace ts { // 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 (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { - const slice = typeArguments.slice(start, i); - const typeArgumentNodes = slice && createNodeArray(mapToTypeNodeArray(slice, context)); + const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + const typeArgumentNodes = typeArgumentSlice && createNodeArray(typeArgumentSlice); const namePart = symbolToTypeReferenceName(parent); (namePart.kind === SyntaxKind.Identifier ? namePart : namePart.right).typeArguments = typeArgumentNodes; @@ -2654,10 +2653,9 @@ namespace ts { } let typeArgumentNodes: TypeNode[] | undefined; - if (some(typeArguments)) { + if (typeArguments.length > 0) { const typeParameterCount = (type.target.typeParameters || emptyArray).length; - const slice = typeArguments && typeArguments.slice(i, typeParameterCount); - typeArgumentNodes = slice && mapToTypeNodeArray(slice, context); + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } if (typeArgumentNodes) { @@ -2740,17 +2738,19 @@ namespace ts { } } - function mapToTypeNodeArray(types: Type[], context: NodeBuilderContext): TypeNode[] { - const result = []; - for (let i = 0; i < types.length; ++i) { - const type = types[i]; - const typeNode = typeToTypeNodeHelper(type, context); - if (typeNode) { - result.push(typeNode); + function mapToTypeNodes(types: Type[], context: NodeBuilderContext): TypeNode[] { + if (some(types)) { + const result = []; + for (let i = 0; i < types.length; ++i) { + const type = types[i]; + const typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } } - } - return result; + return result; + } } function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind, context: NodeBuilderContext): IndexSignatureDeclaration { @@ -2890,9 +2890,7 @@ namespace ts { } } - if (typeParameters && typeParameters.length > 0) { - typeParameterNodes = mapToTypeNodeArray(typeParameters, context); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } const symbolName = getNameOfSymbol(symbol, context); diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 826b636e71e..7917480975e 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2655,7 +2655,7 @@ namespace ts { if (isIdentifier(textSourceNode)) { return getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? `"${escapeString(getTextOfNode(textSourceNode))}"` : - `"${escapeNonAsciiCharacters(escapeString(getTextOfNode(textSourceNode)))}"`; + `"${escapeNonAsciiString(getTextOfNode(textSourceNode))}"`; } else { return getLiteralTextOfNode(textSourceNode); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 18e71f94ee3..1a5f1fbac5f 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3607,16 +3607,17 @@ namespace ts { } export function parenthesizeElementTypeMembers(members: TypeNode[]) { - // TODO: does this lose `originalNode` ptr? - return createNodeArray(members.map(parenthesizeElementTypeMember)); + return createNodeArray(sameMap(members, parenthesizeElementTypeMember)); } export function parenthesizeTypeParameters(typeParameters: TypeNode[]) { - if (typeParameters && typeParameters.length > 0) { - const nodeArray = createNodeArray(typeParameters); - const firstEntry = nodeArray[0]; - if (isFunctionOrConstructor(firstEntry) && firstEntry.typeParameters) { - nodeArray[0] = createParenthesizedType(firstEntry); + if (some(typeParameters)) { + const nodeArray = createNodeArray() as NodeArray; + for (let i = 0; i < typeParameters.length; ++i) { + const entry = typeParameters[i]; + nodeArray.push(i === 0 && isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + createParenthesizedType(entry) : + entry); } return nodeArray; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4bc97c56c00..3ac3caa1216 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -580,7 +580,7 @@ namespace ts { /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace - /*@internal*/ typeArguments?: NodeArray; // Only defined on synthesized nodes.Though not syntactically valid, used in emitting diagnostics. + /*@internal*/ typeArguments?: NodeArray; // Only defined on synthesized nodes. Though not syntactically valid, used in emitting diagnostics. } // Transient identifier node (marked by id === -1) @@ -2599,10 +2599,10 @@ namespace ts { AllowEmptyUnionOrIntersection = 1 << 14, AllowEmptyTuple = 1 << 15, - ignoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple, + IgnoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple, // State - inObjectTypeLiteral = 1 << 20, + InObjectTypeLiteral = 1 << 20, InTypeAlias = 1 << 23, // Writing type in type alias declaration } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 9dac18eec89..c8e481bc2e9 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -328,9 +328,8 @@ namespace ts { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - const escapeText = getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? - (text: string) => escapeString(text) : - (text: string) => escapeNonAsciiCharacters(escapeString(text)); + const escapeText = getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -880,7 +879,7 @@ namespace ts { return false; } - export function isFunctionOrConstructor(node: Node): node is FunctionTypeNode | ConstructorTypeNode { + export function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode { switch (node.kind) { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: @@ -2468,7 +2467,8 @@ namespace ts { } const nonAsciiCharacters = /[^\u0000-\u007F]/g; - export function escapeNonAsciiCharacters(s: string): string { + export function escapeNonAsciiString(s: string): string { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index c62af0da794..f8fe92c184c 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -988,8 +988,6 @@ namespace ts { result = reduceNode((node).initializer, cbNode, result); break; - case SyntaxKind.PropertySignature: - case SyntaxKind.MethodDeclaration: result = reduceNodes((node).decorators, cbNodes, result); result = reduceNodes((node).modifiers, cbNodes, result); From 76955ce792074d3587eeeef825e6bb0f3749563c Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 17 May 2017 07:27:08 -0700 Subject: [PATCH 226/282] Expand tests that jsdoc does not affect typescript code --- .../reference/jsdocInTypeScript.errors.txt | 49 +++++++++++++++++++ .../baselines/reference/jsdocInTypeScript.js | 34 +++++++++++++ .../reference/jsdocInTypeScript.symbols | 19 ------- .../reference/jsdocInTypeScript.types | 19 ------- tests/cases/compiler/jsdocInTypeScript.ts | 21 ++++++++ 5 files changed, 104 insertions(+), 38 deletions(-) create mode 100644 tests/baselines/reference/jsdocInTypeScript.errors.txt delete mode 100644 tests/baselines/reference/jsdocInTypeScript.symbols delete mode 100644 tests/baselines/reference/jsdocInTypeScript.types diff --git a/tests/baselines/reference/jsdocInTypeScript.errors.txt b/tests/baselines/reference/jsdocInTypeScript.errors.txt new file mode 100644 index 00000000000..621aa4677b4 --- /dev/null +++ b/tests/baselines/reference/jsdocInTypeScript.errors.txt @@ -0,0 +1,49 @@ +tests/cases/compiler/jsdocInTypeScript.ts(16,23): error TS2304: Cannot find name 'MyType'. +tests/cases/compiler/jsdocInTypeScript.ts(23,33): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/jsdocInTypeScript.ts(25,3): error TS2345: Argument of type '1' is not assignable to parameter of type 'boolean'. +tests/cases/compiler/jsdocInTypeScript.ts(25,15): error TS2339: Property 'length' does not exist on type 'number'. +tests/cases/compiler/jsdocInTypeScript.ts(30,3): error TS2339: Property 'x' does not exist on type '{}'. + + +==== tests/cases/compiler/jsdocInTypeScript.ts (5 errors) ==== + // JSDoc typedef tags are not bound TypeScript files. + /** @typedef {function} T */ + declare const x: T; + + class T { + prop: number; + } + + x.prop; + + // Just to be sure that @property has no impact either. + /** + * @typedef {Object} MyType + * @property {string} yes + */ + declare const myType: MyType; // should error, no such type + ~~~~~~ +!!! error TS2304: Cannot find name 'MyType'. + + // @param type has no effect. + /** + * @param {number} x + * @returns string + */ + function f(x: boolean) { return x * 2; } // Should error + ~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + // Should fail, because it takes a boolean and returns a number + f(1); f(true).length; + ~ +!!! error TS2345: Argument of type '1' is not assignable to parameter of type 'boolean'. + ~~~~~~ +!!! error TS2339: Property 'length' does not exist on type 'number'. + + // @type has no effect either. + /** @type {{ x?: number }} */ + const z = {}; + z.x = 1; + ~ +!!! error TS2339: Property 'x' does not exist on type '{}'. + \ No newline at end of file diff --git a/tests/baselines/reference/jsdocInTypeScript.js b/tests/baselines/reference/jsdocInTypeScript.js index af4b8b6ce0a..29782e92592 100644 --- a/tests/baselines/reference/jsdocInTypeScript.js +++ b/tests/baselines/reference/jsdocInTypeScript.js @@ -8,6 +8,27 @@ class T { } x.prop; + +// Just to be sure that @property has no impact either. +/** + * @typedef {Object} MyType + * @property {string} yes + */ +declare const myType: MyType; // should error, no such type + +// @param type has no effect. +/** + * @param {number} x + * @returns string + */ +function f(x: boolean) { return x * 2; } // Should error +// Should fail, because it takes a boolean and returns a number +f(1); f(true).length; + +// @type has no effect either. +/** @type {{ x?: number }} */ +const z = {}; +z.x = 1; //// [jsdocInTypeScript.js] @@ -17,3 +38,16 @@ var T = (function () { return T; }()); x.prop; +// @param type has no effect. +/** + * @param {number} x + * @returns string + */ +function f(x) { return x * 2; } // Should error +// Should fail, because it takes a boolean and returns a number +f(1); +f(true).length; +// @type has no effect either. +/** @type {{ x?: number }} */ +var z = {}; +z.x = 1; diff --git a/tests/baselines/reference/jsdocInTypeScript.symbols b/tests/baselines/reference/jsdocInTypeScript.symbols deleted file mode 100644 index 62b6ad3c539..00000000000 --- a/tests/baselines/reference/jsdocInTypeScript.symbols +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/compiler/jsdocInTypeScript.ts === -// JSDoc typedef tags are not bound TypeScript files. -/** @typedef {function} T */ -declare const x: T; ->x : Symbol(x, Decl(jsdocInTypeScript.ts, 2, 13)) ->T : Symbol(T, Decl(jsdocInTypeScript.ts, 2, 19)) - -class T { ->T : Symbol(T, Decl(jsdocInTypeScript.ts, 2, 19)) - - prop: number; ->prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9)) -} - -x.prop; ->x.prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9)) ->x : Symbol(x, Decl(jsdocInTypeScript.ts, 2, 13)) ->prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9)) - diff --git a/tests/baselines/reference/jsdocInTypeScript.types b/tests/baselines/reference/jsdocInTypeScript.types deleted file mode 100644 index 03ff2929e0a..00000000000 --- a/tests/baselines/reference/jsdocInTypeScript.types +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/compiler/jsdocInTypeScript.ts === -// JSDoc typedef tags are not bound TypeScript files. -/** @typedef {function} T */ -declare const x: T; ->x : T ->T : T - -class T { ->T : T - - prop: number; ->prop : number -} - -x.prop; ->x.prop : number ->x : T ->prop : number - diff --git a/tests/cases/compiler/jsdocInTypeScript.ts b/tests/cases/compiler/jsdocInTypeScript.ts index ba9e8dbcbff..08cfb6d5af5 100644 --- a/tests/cases/compiler/jsdocInTypeScript.ts +++ b/tests/cases/compiler/jsdocInTypeScript.ts @@ -7,3 +7,24 @@ class T { } x.prop; + +// Just to be sure that @property has no impact either. +/** + * @typedef {Object} MyType + * @property {string} yes + */ +declare const myType: MyType; // should error, no such type + +// @param type has no effect. +/** + * @param {number} x + * @returns string + */ +function f(x: boolean) { return x * 2; } // Should error +// Should fail, because it takes a boolean and returns a number +f(1); f(true).length; + +// @type has no effect either. +/** @type {{ x?: number }} */ +const z = {}; +z.x = 1; From 0c60824860d8b709611845f818019fa6d1667f7f Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 17 May 2017 08:02:07 -0700 Subject: [PATCH 227/282] Set @typedef parent pointer, but still do not bind a symbol --- src/compiler/binder.ts | 10 ++++------ tests/cases/fourslash/findAllRefsJsDocTypeDef.ts | 9 +++++++++ 2 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsJsDocTypeDef.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 4292b06e775..65cd8e7ae8f 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -439,7 +439,7 @@ namespace ts { // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag && + const isJSDocTypedefInJSDocNamespace = isInJavaScriptFile(node) && node.kind === SyntaxKind.JSDocTypedefTag && (node as JSDocTypedefTag).name && (node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier && ((node as JSDocTypedefTag).name as Identifier).isInJSDocNamespace; @@ -1913,9 +1913,7 @@ namespace ts { // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. - if (isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } + bindJSDocTypedefTagIfAny(node); // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible @@ -2003,7 +2001,7 @@ namespace ts { // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. - if ((node).isInJSDocNamespace) { + if (isInJavaScriptFile(node) && (node).isInJSDocNamespace) { let parentNode = node.parent; while (parentNode && parentNode.kind !== SyntaxKind.JSDocTypedefTag) { parentNode = parentNode.parent; @@ -2149,7 +2147,7 @@ namespace ts { case SyntaxKind.InterfaceDeclaration: return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); case SyntaxKind.JSDocTypedefTag: - if (!(node).fullName || (node).fullName.kind === SyntaxKind.Identifier) { + if (isInJavaScriptFile(node) && (!(node).fullName || (node).fullName.kind === SyntaxKind.Identifier)) { return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); } break; diff --git a/tests/cases/fourslash/findAllRefsJsDocTypeDef.ts b/tests/cases/fourslash/findAllRefsJsDocTypeDef.ts new file mode 100644 index 00000000000..204a4748686 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsJsDocTypeDef.ts @@ -0,0 +1,9 @@ +/// + +// Just testing that this doesn't cause an exception due to the @typedef contents not having '.parent' set. +// But it isn't bound to a Symbol so find-all-refs will return nothing. + +/////** @typedef {Object} [|T|] */ +////function foo() {} + +verify.referenceGroups(test.ranges()[0], undefined); From 0ff187c8aca03f17093a8b3688b9aaf3cc55da2b Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 17 May 2017 08:12:23 -0700 Subject: [PATCH 228/282] Remove 'isDeclarationFile()' function, use '.isDeclarationFile' --- src/compiler/binder.ts | 10 +++++----- src/compiler/declarationEmitter.ts | 2 +- src/compiler/factory.ts | 2 +- src/compiler/program.ts | 13 ++++++------- src/compiler/transformer.ts | 2 +- src/compiler/transformers/es2015.ts | 2 +- src/compiler/transformers/es2016.ts | 2 +- src/compiler/transformers/es2017.ts | 2 +- src/compiler/transformers/esnext.ts | 2 +- src/compiler/transformers/generators.ts | 3 +-- src/compiler/transformers/jsx.ts | 2 +- src/compiler/transformers/module/es2015.ts | 2 +- src/compiler/transformers/module/module.ts | 2 +- src/compiler/transformers/module/system.ts | 4 +--- src/compiler/transformers/ts.ts | 2 +- src/compiler/utilities.ts | 8 ++------ src/harness/projectsRunner.ts | 2 +- 17 files changed, 27 insertions(+), 35 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index b6074162fff..1940231a6d1 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -149,7 +149,7 @@ namespace ts { inStrictMode = bindInStrictMode(file, opts); classifiableNames = createMap(); symbolCount = 0; - skipTransformFlagAggregation = isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = objectAllocator.getSymbolConstructor(); @@ -182,7 +182,7 @@ namespace ts { return bindSourceFile; function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -2527,7 +2527,7 @@ namespace ts { } function bindFunctionDeclaration(node: FunctionDeclaration) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (!file.isDeclarationFile && !isInAmbientContext(node)) { if (isAsyncFunction(node)) { emitFlags |= NodeFlags.HasAsyncFunctions; } @@ -2544,7 +2544,7 @@ namespace ts { } function bindFunctionExpression(node: FunctionExpression) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (!file.isDeclarationFile && !isInAmbientContext(node)) { if (isAsyncFunction(node)) { emitFlags |= NodeFlags.HasAsyncFunctions; } @@ -2558,7 +2558,7 @@ namespace ts { } function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (!file.isDeclarationFile && !isInAmbientContext(node)) { if (isAsyncFunction(node)) { emitFlags |= NodeFlags.HasAsyncFunctions; } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 7c842de277f..4d06b41f377 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1840,7 +1840,7 @@ namespace ts { function writeReferencePath(referencedFile: SourceFile, addBundledFileReference: boolean, emitOnlyDtsFiles: boolean): boolean { let declFileName: string; let addedBundledEmitReference = false; - if (isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index fbb387f034e..270ca0cb4d5 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3858,7 +3858,7 @@ namespace ts { if (file.moduleName) { return createLiteral(file.moduleName); } - if (!isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return createLiteral(getExternalModuleNameFromPath(host, file.fileName)); } return undefined; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 8233ab4802e..2fde21afec6 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1309,7 +1309,7 @@ namespace ts { } function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { - return isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics(): Diagnostic[] { @@ -1348,7 +1348,6 @@ namespace ts { const isJavaScriptFile = isSourceFileJavaScript(file); const isExternalModuleFile = isExternalModule(file); - const isDtsFile = isDeclarationFile(file); let imports: LiteralExpression[]; let moduleAugmentations: LiteralExpression[]; @@ -1401,7 +1400,7 @@ namespace ts { } break; case SyntaxKind.ModuleDeclaration: - if (isAmbientModule(node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || isDeclarationFile(file))) { + if (isAmbientModule(node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || file.isDeclarationFile)) { const moduleName = (node).name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -1412,7 +1411,7 @@ namespace ts { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -1730,7 +1729,7 @@ namespace ts { const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (const sourceFile of sourceFiles) { - if (!isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -1843,13 +1842,13 @@ namespace ts { const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; - const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); + const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !f.isDeclarationFile ? f : undefined); if (options.isolatedModules) { if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); + const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !f.isDeclarationFile ? f : undefined); if (firstNonExternalModuleSourceFile) { const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index bb1732b57ea..75f9c43c6fe 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -165,7 +165,7 @@ namespace ts { }; function transformRoot(node: T) { - return node && (!isSourceFile(node) || !isDeclarationFile(node)) ? transformation(node) : node; + return node && (!isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index ad9a6b99395..63c10145165 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -295,7 +295,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/es2016.ts b/src/compiler/transformers/es2016.ts index 1118e6ad9b6..a9468991776 100644 --- a/src/compiler/transformers/es2016.ts +++ b/src/compiler/transformers/es2016.ts @@ -9,7 +9,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 3bbb3b3123f..3565547d78a 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -47,7 +47,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 81ebd0b8f5b..6e2f70b5c35 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -33,7 +33,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 286892f9d3b..9aadd6bc686 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -293,8 +293,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node) - || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) { + if (node.isDeclarationFile || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) { return node; } diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index e9455490a5d..09f361d1b13 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -15,7 +15,7 @@ namespace ts { * @param node A SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/module/es2015.ts b/src/compiler/transformers/module/es2015.ts index 660293e074f..3951d08109d 100644 --- a/src/compiler/transformers/module/es2015.ts +++ b/src/compiler/transformers/module/es2015.ts @@ -16,7 +16,7 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index d387a1a3a24..b3e544a3f8b 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -55,7 +55,7 @@ namespace ts { * @param node The SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node) || !(isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index 5711d9f1116..3355ad35633 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -50,9 +50,7 @@ namespace ts { * @param node The SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node) - || !(isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 65978409223..a2e8c192da3 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -76,7 +76,7 @@ namespace ts { * @param node A SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 8d570f70639..befb1c4ba77 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -587,10 +587,6 @@ namespace ts { return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } - export function isDeclarationFile(file: SourceFile): boolean { - return file.isDeclarationFile; - } - export function isConstEnumDeclaration(node: Node): boolean { return node.kind === SyntaxKind.EnumDeclaration && isConst(node); } @@ -2575,7 +2571,7 @@ namespace ts { export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): string { const file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -2648,7 +2644,7 @@ namespace ts { /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } /** diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index b0efcf4c389..28d59fe35bd 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -372,7 +372,7 @@ class ProjectRunner extends RunnerBase { const compilerOptions = compilerResult.program.getCompilerOptions(); ts.forEach(compilerResult.program.getSourceFiles(), sourceFile => { - if (ts.isDeclarationFile(sourceFile)) { + if (sourceFile.isDeclarationFile) { allInputFiles.unshift({ emittedFileName: sourceFile.fileName, code: sourceFile.text }); } else if (!(compilerOptions.outFile || compilerOptions.out)) { From b9c3a992e1fb2fc1f437986a9dee113ab6c98f71 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 17 May 2017 08:26:00 -0700 Subject: [PATCH 229/282] getAllPossiblePropertiesOfTypes: Skip primitives --- src/compiler/checker.ts | 4 ++++ src/compiler/types.ts | 1 + tests/cases/fourslash/completionListOfUnion.ts | 2 ++ 3 files changed, 7 insertions(+) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2d464886653..953a72e2ecf 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5785,6 +5785,10 @@ namespace ts { if (type.flags & TypeFlags.Union) { const props = createMap(); for (const memberType of (type as UnionType).types) { + if (memberType.flags & TypeFlags.Primitive) { + continue; + } + for (const { name } of getPropertiesOfType(memberType)) { if (!props.has(name)) { props.set(name, createUnionOrIntersectionProperty(type as UnionType, name)); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 0283c45f2e1..d0962ac41d9 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2587,6 +2587,7 @@ namespace ts { /** * For a union, will include a property if it's defined in *any* of the member types. * So for `{ a } | { b }`, this will include both `a` and `b`. + * Does not include properties of primitive types. */ /* @internal */ getAllPossiblePropertiesOfType(type: Type): Symbol[]; } diff --git a/tests/cases/fourslash/completionListOfUnion.ts b/tests/cases/fourslash/completionListOfUnion.ts index 6026615f8c1..8e6d1f20a32 100644 --- a/tests/cases/fourslash/completionListOfUnion.ts +++ b/tests/cases/fourslash/completionListOfUnion.ts @@ -10,9 +10,11 @@ ////f({ /*f*/ }); goTo.marker("x"); +verify.completionListCount(3); verify.completionListContains("a", "(property) a: string | number"); verify.completionListContains("b", "(property) b: number | boolean"); verify.completionListContains("c", "(property) c: string"); goTo.marker("f"); verify.completionListContains("a", "(property) a: number"); +// Also contains array members From 6a7b6d367b9a2b85e9389b598aa06d7f2ad45d75 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 May 2017 11:59:33 -0700 Subject: [PATCH 230/282] Accept new baselines --- tests/baselines/reference/enumErrors.errors.txt | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/baselines/reference/enumErrors.errors.txt b/tests/baselines/reference/enumErrors.errors.txt index 096722fc4bd..af719d47ae2 100644 --- a/tests/baselines/reference/enumErrors.errors.txt +++ b/tests/baselines/reference/enumErrors.errors.txt @@ -7,10 +7,10 @@ tests/cases/conformance/enums/enumErrors.ts(26,9): error TS2322: Type 'true' is tests/cases/conformance/enums/enumErrors.ts(27,9): error TS2322: Type 'Date' is not assignable to type 'E11'. tests/cases/conformance/enums/enumErrors.ts(28,9): error TS2304: Cannot find name 'window'. tests/cases/conformance/enums/enumErrors.ts(29,9): error TS2322: Type '{}' is not assignable to type 'E11'. -tests/cases/conformance/enums/enumErrors.ts(35,9): error TS2551: Computed values are not permitted in an enum with string valued members. -tests/cases/conformance/enums/enumErrors.ts(36,9): error TS2551: Computed values are not permitted in an enum with string valued members. -tests/cases/conformance/enums/enumErrors.ts(37,9): error TS2551: Computed values are not permitted in an enum with string valued members. -tests/cases/conformance/enums/enumErrors.ts(38,9): error TS2551: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(35,9): error TS2553: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(36,9): error TS2553: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(37,9): error TS2553: Computed values are not permitted in an enum with string valued members. +tests/cases/conformance/enums/enumErrors.ts(38,9): error TS2553: Computed values are not permitted in an enum with string valued members. ==== tests/cases/conformance/enums/enumErrors.ts (13 errors) ==== @@ -68,15 +68,15 @@ tests/cases/conformance/enums/enumErrors.ts(38,9): error TS2551: Computed values A = '', B = new Date(), ~~~~~~~~~~ -!!! error TS2551: Computed values are not permitted in an enum with string valued members. +!!! error TS2553: Computed values are not permitted in an enum with string valued members. C = window, ~~~~~~ -!!! error TS2551: Computed values are not permitted in an enum with string valued members. +!!! error TS2553: Computed values are not permitted in an enum with string valued members. D = {}, ~~ -!!! error TS2551: Computed values are not permitted in an enum with string valued members. +!!! error TS2553: Computed values are not permitted in an enum with string valued members. E = 1 + 1, ~~~~~ -!!! error TS2551: Computed values are not permitted in an enum with string valued members. +!!! error TS2553: Computed values are not permitted in an enum with string valued members. } \ No newline at end of file From c4c9bf70c429fd5a22537691f841cfc5867db0b9 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 17 May 2017 12:51:37 -0700 Subject: [PATCH 231/282] Add `| undefined` to test --- tests/cases/fourslash/completionListOfUnion.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/cases/fourslash/completionListOfUnion.ts b/tests/cases/fourslash/completionListOfUnion.ts index 8e6d1f20a32..5ffaf89e5b3 100644 --- a/tests/cases/fourslash/completionListOfUnion.ts +++ b/tests/cases/fourslash/completionListOfUnion.ts @@ -2,8 +2,8 @@ // @strictNullChecks: true -// Non-objects should be skipped, so `| number | null` should have no effect on completions. -////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null = { /*x*/ }; +// Primitives should be skipped, so `| number | null | undefined` should have no effect on completions. +////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null | undefined = { /*x*/ }; ////interface I { a: number; } ////function f(...args: Array) {} From ab3ffa22daa4b584410921ee41a27dfea4f9913c Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Wed, 17 May 2017 19:52:57 -0700 Subject: [PATCH 232/282] Add flag to allow local plugin loading --- src/server/editorServices.ts | 3 +++ src/server/project.ts | 6 ++++++ src/server/server.ts | 8 ++++++-- src/server/session.ts | 4 +++- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 4699e1a1d4d..d8322f5e7c5 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -283,6 +283,7 @@ namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } export class ProjectService { @@ -342,6 +343,7 @@ namespace ts.server { public readonly globalPlugins: ReadonlyArray; public readonly pluginProbeLocations: ReadonlyArray; + public readonly allowLocalPluginLoads: boolean; constructor(opts: ProjectServiceOptions) { this.host = opts.host; @@ -353,6 +355,7 @@ namespace ts.server { this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); diff --git a/src/server/project.ts b/src/server/project.ts index 56c394379a0..6372d1f5c03 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -873,6 +873,12 @@ namespace ts.server { // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ const searchPaths = [combinePaths(host.getExecutingFilePath(), "../../.."), ...this.projectService.pluginProbeLocations]; + if (this.projectService.allowLocalPluginLoads) { + const local = getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info(`Local plugin loading enabled; adding ${local} to search paths`); + searchPaths.unshift(local); + } + // Enable tsconfig-specified plugins if (options.plugins) { for (const pluginConfigEntry of options.plugins) { diff --git a/src/server/server.ts b/src/server/server.ts index 67640e430d8..ed3e2dd8207 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -16,6 +16,7 @@ namespace ts.server { telemetryEnabled: boolean; globalPlugins: string[]; pluginProbeLocations: string[]; + allowLocalPluginLoads: boolean; } const net: { @@ -403,7 +404,8 @@ namespace ts.server { logger, canUseEvents, globalPlugins: options.globalPlugins, - pluginProbeLocations: options.pluginProbeLocations}); + pluginProbeLocations: options.pluginProbeLocations, + allowLocalPluginLoads: options.allowLocalPluginLoads }); if (telemetryEnabled && typingsInstaller) { typingsInstaller.setTelemetrySender(this); @@ -743,6 +745,7 @@ namespace ts.server { const globalPlugins = (findArgument("--globalPlugins") || "").split(","); const pluginProbeLocations = (findArgument("--pluginProbeLocations") || "").split(","); + const allowLocalPluginLoads = hasArgument("--allowLocalPluginLoads"); const useSingleInferredProject = hasArgument("--useSingleInferredProject"); const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition"); @@ -760,7 +763,8 @@ namespace ts.server { telemetryEnabled, logger, globalPlugins, - pluginProbeLocations + pluginProbeLocations, + allowLocalPluginLoads }; const ioSession = new IOSession(options); diff --git a/src/server/session.ts b/src/server/session.ts index ca036f4dfe0..7be33f8bd2a 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -348,6 +348,7 @@ namespace ts.server { globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } export class Session implements EventSender { @@ -401,7 +402,8 @@ namespace ts.server { throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new ProjectService(settings); this.gcTimer = new GcTimer(this.host, /*delay*/ 7000, this.logger); From 5a5fee3bb8c33fc1998ed26924c93db13f1ddd05 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 18 May 2017 09:10:11 -0700 Subject: [PATCH 233/282] Declaration-emit class expressions as type literals This works pretty well. Note that circular references bottom out as `any`. Right now this happens for all type writing, not just for declaration emit, but this is probably an improvement on average. --- src/compiler/checker.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7d6c6a725ab..d10a07ad6b7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3266,6 +3266,9 @@ namespace ts { writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), SyntaxKind.CommaToken); writePunctuation(writer, SyntaxKind.CloseBracketToken); } + else if (type.symbol.valueDeclaration && type.symbol.valueDeclaration.kind === SyntaxKind.ClassExpression) { + writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + } else { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those @@ -3313,7 +3316,7 @@ namespace ts { const symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) && symbol.valueDeclaration.kind !== SyntaxKind.ClassExpression || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule)) { writeTypeOfSymbol(type, flags); } @@ -3335,12 +3338,23 @@ namespace ts { else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type + // However, in case of class expressions, we want to write both the static side and the instance side. + // We skip adding the static side so that the instance side has a chance to be written + // before checking for circular references. if (!symbolStack) { symbolStack = []; } - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); + const isConstructorObject = type.flags & TypeFlags.Object && + getObjectFlags(type) & ObjectFlags.Anonymous && + type.symbol && type.symbol.flags & SymbolFlags.Class; + if (isConstructorObject) { + writeLiteralType(type, flags); + } + else { + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } } } else { From e77024915e2aa7d50696511575f20d1f88243ec1 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 18 May 2017 09:11:26 -0700 Subject: [PATCH 234/282] Test:decl emit for class expressions as type lits Add test and update baselines --- ...arationEmitExpressionInExtends4.errors.txt | 8 +- .../emitClassExpressionInDeclarationFile.js | 148 ++++++++++++++++++ ...itClassExpressionInDeclarationFile.symbols | 84 ++++++++++ ...emitClassExpressionInDeclarationFile.types | 91 +++++++++++ .../emitClassExpressionInDeclarationFile.ts | 30 ++++ ...findAllRefsForVariableInExtendsClause01.ts | 2 +- tests/cases/fourslash/renameJsExports02.ts | 4 +- 7 files changed, 357 insertions(+), 10 deletions(-) create mode 100644 tests/baselines/reference/emitClassExpressionInDeclarationFile.js create mode 100644 tests/baselines/reference/emitClassExpressionInDeclarationFile.symbols create mode 100644 tests/baselines/reference/emitClassExpressionInDeclarationFile.types create mode 100644 tests/cases/compiler/emitClassExpressionInDeclarationFile.ts diff --git a/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt b/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt index 54905212836..569e5aa355f 100644 --- a/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt +++ b/tests/baselines/reference/declarationEmitExpressionInExtends4.errors.txt @@ -1,23 +1,17 @@ -tests/cases/compiler/declarationEmitExpressionInExtends4.ts(1,10): error TS4060: Return type of exported function has or is using private name 'D'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,17): error TS2315: Type 'D' is not generic. -tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,17): error TS4020: 'extends' clause of exported class 'C' has or is using private name 'D'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(9,18): error TS2304: Cannot find name 'SomeUndefinedFunction'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS2304: Cannot find name 'SomeUndefinedFunction'. tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS4020: 'extends' clause of exported class 'C3' has or is using private name 'SomeUndefinedFunction'. -==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (6 errors) ==== +==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (4 errors) ==== function getSomething() { - ~~~~~~~~~~~~ -!!! error TS4060: Return type of exported function has or is using private name 'D'. return class D { } } class C extends getSomething() { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2315: Type 'D' is not generic. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS4020: 'extends' clause of exported class 'C' has or is using private name 'D'. } diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile.js b/tests/baselines/reference/emitClassExpressionInDeclarationFile.js new file mode 100644 index 00000000000..423546bcd4e --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile.js @@ -0,0 +1,148 @@ +//// [emitClassExpressionInDeclarationFile.ts] +export var simpleExample = class { + static getTags() { } + tags() { } +} +export var circularReference = class C { + static getTags(c: C): C { return c } + tags(c: C): C { return c } +} + +// repro from #15066 +export class FooItem { + foo(): void { } + name?: string; +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); + + +//// [emitClassExpressionInDeclarationFile.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +exports.simpleExample = (function () { + function class_1() { + } + class_1.getTags = function () { }; + class_1.prototype.tags = function () { }; + return class_1; +}()); +exports.circularReference = (function () { + function C() { + } + C.getTags = function (c) { return c; }; + C.prototype.tags = function (c) { return c; }; + return C; +}()); +// repro from #15066 +var FooItem = (function () { + function FooItem() { + } + FooItem.prototype.foo = function () { }; + return FooItem; +}()); +exports.FooItem = FooItem; +function WithTags(Base) { + return (function (_super) { + __extends(class_2, _super); + function class_2() { + return _super !== null && _super.apply(this, arguments) || this; + } + class_2.getTags = function () { }; + class_2.prototype.tags = function () { }; + return class_2; + }(Base)); +} +exports.WithTags = WithTags; +var Test = (function (_super) { + __extends(Test, _super); + function Test() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Test; +}(WithTags(FooItem))); +exports.Test = Test; +var test = new Test(); +Test.getTags(); +test.tags(); + + +//// [emitClassExpressionInDeclarationFile.d.ts] +export declare var simpleExample: { + new (): { + tags(): void; + }; + prototype: { + tags(): void; + }; + getTags(): void; +}; +export declare var circularReference: { + new (): { + tags(c: any): any; + }; + prototype: { + tags(c: any): any; + }; + getTags(c: { + tags(c: any): any; + }): { + tags(c: any): any; + }; +}; +export declare class FooItem { + foo(): void; + name?: string; +} +export declare type Constructor = new (...args: any[]) => T; +export declare function WithTags>(Base: T): { + new (...args: any[]): { + tags(): void; + foo(): void; + name?: string; + }; + prototype: { + tags(): void; + foo(): void; + name?: string; + }; + getTags(): void; +} & T; +declare const Test_base: { + new (...args: any[]): { + tags(): void; + foo(): void; + name?: string; + }; + prototype: { + tags(): void; + foo(): void; + name?: string; + }; + getTags(): void; +} & typeof FooItem; +export declare class Test extends Test_base { +} diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile.symbols b/tests/baselines/reference/emitClassExpressionInDeclarationFile.symbols new file mode 100644 index 00000000000..537838937c5 --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile.symbols @@ -0,0 +1,84 @@ +=== tests/cases/compiler/emitClassExpressionInDeclarationFile.ts === +export var simpleExample = class { +>simpleExample : Symbol(simpleExample, Decl(emitClassExpressionInDeclarationFile.ts, 0, 10)) + + static getTags() { } +>getTags : Symbol(simpleExample.getTags, Decl(emitClassExpressionInDeclarationFile.ts, 0, 34)) + + tags() { } +>tags : Symbol(simpleExample.tags, Decl(emitClassExpressionInDeclarationFile.ts, 1, 24)) +} +export var circularReference = class C { +>circularReference : Symbol(circularReference, Decl(emitClassExpressionInDeclarationFile.ts, 4, 10)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) + + static getTags(c: C): C { return c } +>getTags : Symbol(C.getTags, Decl(emitClassExpressionInDeclarationFile.ts, 4, 40)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 5, 19)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 5, 19)) + + tags(c: C): C { return c } +>tags : Symbol(C.tags, Decl(emitClassExpressionInDeclarationFile.ts, 5, 40)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 6, 9)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30)) +>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 6, 9)) +} + +// repro from #15066 +export class FooItem { +>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1)) + + foo(): void { } +>foo : Symbol(FooItem.foo, Decl(emitClassExpressionInDeclarationFile.ts, 10, 22)) + + name?: string; +>name : Symbol(FooItem.name, Decl(emitClassExpressionInDeclarationFile.ts, 11, 19)) +} + +export type Constructor = new(...args: any[]) => T; +>Constructor : Symbol(Constructor, Decl(emitClassExpressionInDeclarationFile.ts, 13, 1)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 15, 24)) +>args : Symbol(args, Decl(emitClassExpressionInDeclarationFile.ts, 15, 33)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 15, 24)) + +export function WithTags>(Base: T) { +>WithTags : Symbol(WithTags, Decl(emitClassExpressionInDeclarationFile.ts, 15, 54)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 16, 25)) +>Constructor : Symbol(Constructor, Decl(emitClassExpressionInDeclarationFile.ts, 13, 1)) +>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1)) +>Base : Symbol(Base, Decl(emitClassExpressionInDeclarationFile.ts, 16, 57)) +>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 16, 25)) + + return class extends Base { +>Base : Symbol(Base, Decl(emitClassExpressionInDeclarationFile.ts, 16, 57)) + + static getTags(): void { } +>getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31)) + + tags(): void { } +>tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34)) + } +} + +export class Test extends WithTags(FooItem) {} +>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1)) +>WithTags : Symbol(WithTags, Decl(emitClassExpressionInDeclarationFile.ts, 15, 54)) +>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1)) + +const test = new Test(); +>test : Symbol(test, Decl(emitClassExpressionInDeclarationFile.ts, 25, 5)) +>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1)) + +Test.getTags() +>Test.getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31)) +>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1)) +>getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31)) + +test.tags(); +>test.tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34)) +>test : Symbol(test, Decl(emitClassExpressionInDeclarationFile.ts, 25, 5)) +>tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34)) + diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile.types b/tests/baselines/reference/emitClassExpressionInDeclarationFile.types new file mode 100644 index 00000000000..3d5190262de --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile.types @@ -0,0 +1,91 @@ +=== tests/cases/compiler/emitClassExpressionInDeclarationFile.ts === +export var simpleExample = class { +>simpleExample : typeof simpleExample +>class { static getTags() { } tags() { }} : typeof simpleExample + + static getTags() { } +>getTags : () => void + + tags() { } +>tags : () => void +} +export var circularReference = class C { +>circularReference : typeof C +>class C { static getTags(c: C): C { return c } tags(c: C): C { return c }} : typeof C +>C : typeof C + + static getTags(c: C): C { return c } +>getTags : (c: C) => C +>c : C +>C : C +>C : C +>c : C + + tags(c: C): C { return c } +>tags : (c: C) => C +>c : C +>C : C +>C : C +>c : C +} + +// repro from #15066 +export class FooItem { +>FooItem : FooItem + + foo(): void { } +>foo : () => void + + name?: string; +>name : string +} + +export type Constructor = new(...args: any[]) => T; +>Constructor : Constructor +>T : T +>args : any[] +>T : T + +export function WithTags>(Base: T) { +>WithTags : >(Base: T) => { new (...args: any[]): (Anonymous class); prototype: WithTags.(Anonymous class); getTags(): void; } & T +>T : T +>Constructor : Constructor +>FooItem : FooItem +>Base : T +>T : T + + return class extends Base { +>class extends Base { static getTags(): void { } tags(): void { } } : { new (...args: any[]): (Anonymous class); prototype: WithTags.(Anonymous class); getTags(): void; } & T +>Base : FooItem + + static getTags(): void { } +>getTags : () => void + + tags(): void { } +>tags : () => void + } +} + +export class Test extends WithTags(FooItem) {} +>Test : Test +>WithTags(FooItem) : WithTags.(Anonymous class) & FooItem +>WithTags : >(Base: T) => { new (...args: any[]): (Anonymous class); prototype: WithTags.(Anonymous class); getTags(): void; } & T +>FooItem : typeof FooItem + +const test = new Test(); +>test : Test +>new Test() : Test +>Test : typeof Test + +Test.getTags() +>Test.getTags() : void +>Test.getTags : () => void +>Test : typeof Test +>getTags : () => void + +test.tags(); +>test.tags() : void +>test.tags : () => void +>test : Test +>tags : () => void + diff --git a/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts new file mode 100644 index 00000000000..f99bcbd7efd --- /dev/null +++ b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts @@ -0,0 +1,30 @@ +// @declaration: true +export var simpleExample = class { + static getTags() { } + tags() { } +} +export var circularReference = class C { + static getTags(c: C): C { return c } + tags(c: C): C { return c } +} + +// repro from #15066 +export class FooItem { + foo(): void { } + name?: string; +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); diff --git a/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts b/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts index a61f925c97e..9d79d97d419 100644 --- a/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts +++ b/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts @@ -3,4 +3,4 @@ ////var [|{| "isWriteAccess": true, "isDefinition": true |}Base|] = class { }; ////class C extends [|Base|] { } -verify.singleReferenceGroup("var Base: typeof Base"); +verify.singleReferenceGroup("var Base: {\n new (): {};\n prototype: {};\n}"); diff --git a/tests/cases/fourslash/renameJsExports02.ts b/tests/cases/fourslash/renameJsExports02.ts index 94c84980784..ef39bbc83b6 100644 --- a/tests/cases/fourslash/renameJsExports02.ts +++ b/tests/cases/fourslash/renameJsExports02.ts @@ -10,7 +10,7 @@ const [r0, r1] = test.ranges(); verify.referenceGroups(r0, [ { definition: "(local class) A", ranges: [r0] }, - { definition: "const A: typeof A", ranges: [r1] } + { definition: "const A: {\n new (): {};\n prototype: {};\n}", ranges: [r1] } ]); -verify.singleReferenceGroup("const A: typeof A", [r1]); +verify.singleReferenceGroup("const A: {\n new (): {};\n prototype: {};\n}", [r1]); From 42d89681e9f69c40883f1c5a84db19fb22bff27c Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 18 May 2017 11:04:27 -0700 Subject: [PATCH 235/282] Finish botched merge from master --- src/compiler/diagnosticMessages.json | 2 +- .../reference/ES5SymbolProperty5.errors.txt | 4 +- ...signingFromObjectToAnythingElse.errors.txt | 8 +- .../baselines/reference/baseCheck.errors.txt | 4 +- ...dSameNameFunctionDeclarationES5.errors.txt | 16 ++-- ...dSameNameFunctionDeclarationES6.errors.txt | 16 ++-- ...ameFunctionDeclarationStrictES5.errors.txt | 16 ++-- ...ameFunctionDeclarationStrictES6.errors.txt | 16 ++-- ...hIncorrectNumberOfTypeArguments.errors.txt | 56 ++++++------- ...enericFunctionWithTypeArguments.errors.txt | 28 +++---- .../reference/callOnInstance.errors.txt | 4 +- .../reference/callWithSpread2.errors.txt | 12 +-- ...lWithWrongNumberOfTypeArguments.errors.txt | 8 +- ...ssWithBaseClassButNoConstructor.errors.txt | 16 ++-- .../classWithConstructors.errors.txt | 24 +++--- ...classWithoutExplicitConstructor.errors.txt | 8 +- .../reference/cloduleTest2.errors.txt | 16 ++-- ...ericRecursiveBaseClassReference.errors.txt | 4 +- ...torInvocationWithTooFewTypeArgs.errors.txt | 4 +- .../couldNotSelectGenericOverload.errors.txt | 8 +- ...ClassWithoutExplicitConstructor.errors.txt | 8 +- ...lassWithoutExplicitConstructor2.errors.txt | 8 +- ...lassWithoutExplicitConstructor3.errors.txt | 16 ++-- ...llingBaseImplWithOptionalParams.errors.txt | 4 +- .../emptyTypeArgumentList.errors.txt | 4 +- .../emptyTypeArgumentListWithNew.errors.txt | 4 +- ...rdReferenceForwadingConstructor.errors.txt | 4 +- .../reference/functionCall11.errors.txt | 8 +- .../reference/functionCall12.errors.txt | 4 +- .../reference/functionCall13.errors.txt | 4 +- .../reference/functionCall16.errors.txt | 4 +- .../reference/functionCall17.errors.txt | 4 +- .../reference/functionCall6.errors.txt | 8 +- .../reference/functionCall7.errors.txt | 8 +- .../reference/functionCall8.errors.txt | 4 +- .../reference/functionCall9.errors.txt | 4 +- ...functionConstraintSatisfaction2.errors.txt | 8 +- .../reference/functionOverloads29.errors.txt | 4 +- .../reference/functionOverloads34.errors.txt | 4 +- .../reference/functionOverloads37.errors.txt | 4 +- ...kedInsideItsContainingFunction1.errors.txt | 24 +++--- .../genericDefaultsErrors.errors.txt | 8 +- ...unctionsWithOptionalParameters2.errors.txt | 4 +- .../genericWithOpenTypeParameters1.errors.txt | 8 +- .../reference/grammarAmbiguities.errors.txt | 8 +- .../reference/grammarAmbiguities1.errors.txt | 8 +- ...sWithWrongNumberOfTypeArguments.errors.txt | 8 +- ...NonGenericTypeWithTypeArguments.errors.txt | 12 +-- .../reference/iteratorSpreadInCall.errors.txt | 4 +- .../iteratorSpreadInCall10.errors.txt | 4 +- .../iteratorSpreadInCall2.errors.txt | 4 +- .../iteratorSpreadInCall4.errors.txt | 4 +- ...leFunctionParametersAsOptional2.errors.txt | 12 +-- ...citTypeParameterAndArgumentType.errors.txt | 4 +- .../optionalParamArgsTest.errors.txt | 80 +++++++++---------- .../baselines/reference/overload1.errors.txt | 8 +- .../reference/overloadResolution.errors.txt | 4 +- ...loadResolutionClassConstructors.errors.txt | 12 +-- .../overloadResolutionConstructors.errors.txt | 4 +- ...ResolutionOnDefaultConstructor1.errors.txt | 4 +- ...loadsAndTypeArgumentArityErrors.errors.txt | 8 +- .../parserConstructorAmbiguity3.errors.txt | 4 +- ...IOnCallAfterFunctionExpression1.errors.txt | 4 +- .../recursiveFunctionTypes.errors.txt | 8 +- .../requiredInitializedParameter1.errors.txt | 8 +- .../restParamsWithNonRestParams.errors.txt | 4 +- ...eStringsWithOverloadResolution1.errors.txt | 8 +- ...ingsWithOverloadResolution1_ES6.errors.txt | 8 +- ...eStringsWithOverloadResolution3.errors.txt | 4 +- ...ingsWithOverloadResolution3_ES6.errors.txt | 4 +- ...hIncompleteTemplateExpressions4.errors.txt | 4 +- ...hIncompleteTemplateExpressions5.errors.txt | 4 +- ...CallExpressionWithTypeArguments.errors.txt | 4 +- .../thisTypeInFunctionsNegative.errors.txt | 40 +++++----- .../tooManyTypeParameters1.errors.txt | 12 +-- ...OnFunctionsWithNoTypeParameters.errors.txt | 8 +- ...eAssertionToGenericFunctionType.errors.txt | 4 +- .../reference/typeAssertions.errors.txt | 4 +- .../typesWithPublicConstructor.errors.txt | 4 +- .../unionTypeCallSignatures.errors.txt | 68 ++++++++-------- .../unionTypeCallSignatures4.errors.txt | 16 ++-- .../unionTypeConstructSignatures.errors.txt | 64 +++++++-------- ...unctionCallsWithTypeParameters1.errors.txt | 16 ++-- 83 files changed, 459 insertions(+), 459 deletions(-) diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 8defed492f6..ffedb45c2e0 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1869,7 +1869,7 @@ }, "Expected {0} arguments, but got a minimum of {1}.": { "category": "Error", - "code": 2555 + "code": 2556 }, "Expected at least {0} arguments, but got a minimum of {1}.": { "category": "Error", diff --git a/tests/baselines/reference/ES5SymbolProperty5.errors.txt b/tests/baselines/reference/ES5SymbolProperty5.errors.txt index 278374e417d..fb3a9aa78d4 100644 --- a/tests/baselines/reference/ES5SymbolProperty5.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2553: Expected 0 arguments, but got 1. +tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/conformance/Symbols/ES5SymbolProperty5.ts (1 errors) ==== @@ -10,4 +10,4 @@ tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,1): error TS2553: Expect (new C)[Symbol.iterator](0) // Should error ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. \ No newline at end of file +!!! error TS2554: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt index d476f1f08e2..c8fb57e3616 100644 --- a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt +++ b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(3,1): error TS2322: Type 'Object' is not assignable to type 'RegExp'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'exec' is missing in type 'Object'. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,17): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,17): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Type 'Object' is not assignable to type 'Error'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'name' is missing in type 'Object'. @@ -19,10 +19,10 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Ty var a: String = Object.create(""); ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var c: String = Object.create(1); ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var w: Error = new Object(); ~ diff --git a/tests/baselines/reference/baseCheck.errors.txt b/tests/baselines/reference/baseCheck.errors.txt index cf1da0a5358..0ae410d4e34 100644 --- a/tests/baselines/reference/baseCheck.errors.txt +++ b/tests/baselines/reference/baseCheck.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/baseCheck.ts(9,18): error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'? -tests/cases/compiler/baseCheck.ts(17,53): error TS2553: Expected 2 arguments, but got 1. +tests/cases/compiler/baseCheck.ts(17,53): error TS2554: Expected 2 arguments, but got 1. tests/cases/compiler/baseCheck.ts(17,59): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/baseCheck.ts(18,62): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/baseCheck.ts(19,59): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. @@ -30,7 +30,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'. class D extends C { constructor(public z: number) { super(this.z) } } // too few params ~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. ~~~~ !!! error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. class E extends C { constructor(public z: number) { super(0, this.z) } } diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt index fe9bc6700fb..77dc618f912 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(3,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(5,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(5,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(8,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(10,9): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(12,5): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(10,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(12,5): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts (6 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } // duplicate function @@ -24,14 +24,14 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. foo(); } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt index 6df85e1495a..c9a8c67296a 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(3,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(5,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(5,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(8,18): error TS2393: Duplicate function implementation. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(10,9): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(12,5): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(10,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(12,5): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts (6 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } // duplicate @@ -24,14 +24,14 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(); foo(10);// not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. foo(); } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt index 0647034272d..fb53f7a8f96 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(4,18): error TS1250: Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(6,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(6,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(9,18): error TS1250: Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(11,9): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(14,5): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(11,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(14,5): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts (6 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } // Error to declare function in block scope @@ -25,14 +25,14 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt index 32da909c2fe..ae2bdcf587f 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(6,9): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(11,9): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(14,5): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(6,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(11,9): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(14,5): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts (4 errors) ==== @@ -12,21 +12,21 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): e foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } else { function foo() { } foo(); foo(10); // not ok ~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } foo(10); foo(); // not ok ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt index 99fc058d8bd..6d95b588ebf 100644 --- a/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callGenericFunctionWithIncorrectNumberOfTypeArguments.errors.txt @@ -1,17 +1,17 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2557: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2557: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2557: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2557: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2557: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2557: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2557: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2557: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2557: Expected 2 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2557: Expected 2 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2557: Expected 0 type arguments, but got 3. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2557: Expected 0 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(5,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(6,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(9,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(10,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(13,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(14,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(21,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(22,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(28,10): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(29,11): error TS2558: Expected 2 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(36,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(37,11): error TS2558: Expected 0 type arguments, but got 3. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(43,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts(44,11): error TS2558: Expected 0 type arguments, but got 3. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFunctionWithIncorrectNumberOfTypeArguments.ts (14 errors) ==== @@ -21,26 +21,26 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti function f(x: T, y: U): T { return null; } var r1 = f(1, ''); ~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. var r1b = f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 3. +!!! error TS2558: Expected 2 type arguments, but got 3. var f2 = (x: T, y: U): T => { return null; } var r2 = f2(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. var r2b = f2(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 3. +!!! error TS2558: Expected 2 type arguments, but got 3. var f3: { (x: T, y: U): T; } var r3 = f3(1, ''); ~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. var r3b = f3(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 3. +!!! error TS2558: Expected 2 type arguments, but got 3. class C { f(x: T, y: U): T { @@ -49,10 +49,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r4 = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. var r4b = (new C()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 3. +!!! error TS2558: Expected 2 type arguments, but got 3. interface I { f(x: T, y: U): T; @@ -60,10 +60,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i: I; var r5 = i.f(1, ''); ~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. var r5b = i.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 3. +!!! error TS2558: Expected 2 type arguments, but got 3. class C2 { f(x: T, y: U): T { @@ -72,10 +72,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti } var r6 = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r6b = (new C2()).f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 3. +!!! error TS2558: Expected 0 type arguments, but got 3. interface I2 { f(x: T, y: U): T; @@ -83,7 +83,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callGenericFuncti var i2: I2; var r7 = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r7b = i2.f(1, ''); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 3. \ No newline at end of file +!!! error TS2558: Expected 0 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt index 72f9908fcee..b014eae0fd8 100644 --- a/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt +++ b/tests/baselines/reference/callNonGenericFunctionWithTypeArguments.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(5,9): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(8,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(11,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(18,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(24,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(31,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(37,10): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(40,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFunctionWithTypeArguments.ts(43,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,17 +16,17 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun function f(x: number) { return null; } var r = f(1); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var f2 = (x: number) => { return null; } var r2 = f2(1); ~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var f3: { (x: number): any; } var r3 = f3(1); ~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. class C { f(x: number) { @@ -35,7 +35,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r4 = (new C()).f(1); ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. interface I { f(x: number): any; @@ -43,7 +43,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i: I; var r5 = i.f(1); ~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. class C2 { f(x: number) { @@ -52,7 +52,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun } var r6 = (new C2()).f(1); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. interface I2 { f(x: number); @@ -60,7 +60,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/callNonGenericFun var i2: I2; var r7 = i2.f(1); ~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var a; var r8 = a(); diff --git a/tests/baselines/reference/callOnInstance.errors.txt b/tests/baselines/reference/callOnInstance.errors.txt index 742303d5cf0..5a6bb31ca28 100644 --- a/tests/baselines/reference/callOnInstance.errors.txt +++ b/tests/baselines/reference/callOnInstance.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/callOnInstance.ts(1,18): error TS2300: Duplicate identifier 'D'. tests/cases/compiler/callOnInstance.ts(3,15): error TS2300: Duplicate identifier 'D'. tests/cases/compiler/callOnInstance.ts(7,19): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/compiler/callOnInstance.ts(7,19): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/callOnInstance.ts(7,19): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/callOnInstance.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'C' has no compatible call signatures. @@ -20,7 +20,7 @@ tests/cases/compiler/callOnInstance.ts(10,1): error TS2349: Cannot invoke an exp ~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. declare class C { constructor(value: number); } (new C(1))(); // Error for calling an instance diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt index cfea427a2a7..89617ab6074 100644 --- a/tests/baselines/reference/callWithSpread2.errors.txt +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -10,9 +10,9 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,11): err Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(35,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(37,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(38,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,1): error TS2556: Expected 1-3 arguments, but got a minimum of 0. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(37,1): error TS2556: Expected 1-3 arguments, but got a minimum of 0. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(38,1): error TS2556: Expected 1-3 arguments, but got a minimum of 0. ==== tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts (9 errors) ==== @@ -71,11 +71,11 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(38,1): erro !!! error TS2345: Type 'string' is not assignable to type 'number'. prefix(...ns) // required parameters are required ~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2556: Expected 1-3 arguments, but got a minimum of 0. prefix(...mixed) ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2556: Expected 1-3 arguments, but got a minimum of 0. prefix(...tuple) ~~~~~~~~~~~~~~~~ -!!! error TS2346: Supplied parameters do not match any signature of call target. +!!! error TS2556: Expected 1-3 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt index 87fe7f62acf..e3fca9dff9c 100644 --- a/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/callWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2557: Expected 2 type arguments, but got 1. -tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2557: Expected 2 type arguments, but got 3. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(3,1): error TS2558: Expected 2 type arguments, but got 1. +tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2558: Expected 2 type arguments, but got 3. ==== tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -7,8 +7,8 @@ tests/cases/compiler/callWithWrongNumberOfTypeArguments.ts(5,1): error TS2557: E f(); ~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. f(); f(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 3. \ No newline at end of file +!!! error TS2558: Expected 2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt index 197e38bdae1..da4c3a16f8b 100644 --- a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt +++ b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(10,9): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(22,9): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(31,10): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(39,10): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(10,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(22,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(31,10): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts(39,10): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts (4 errors) ==== @@ -16,7 +16,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r = C; var c = new C(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var c2 = new C(1); // ok class Base2 { @@ -30,7 +30,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r2 = D; var d = new D(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new D(1); // ok // specialized base class @@ -41,7 +41,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r3 = D2; var d3 = new D(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var d4 = new D(1); // ok class D3 extends Base2 { @@ -51,5 +51,5 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var r4 = D3; var d5 = new D(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var d6 = new D(1); // ok \ No newline at end of file diff --git a/tests/baselines/reference/classWithConstructors.errors.txt b/tests/baselines/reference/classWithConstructors.errors.txt index b637775876a..870d8ef13da 100644 --- a/tests/baselines/reference/classWithConstructors.errors.txt +++ b/tests/baselines/reference/classWithConstructors.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(6,13): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(15,14): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(21,13): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(31,13): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(40,14): error TS2553: Expected 1-2 arguments, but got 0. -tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(46,13): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(6,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(15,14): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(21,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(31,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(40,14): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts(46,13): error TS2554: Expected 1-2 arguments, but got 0. ==== tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts (6 errors) ==== @@ -14,7 +14,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var c2 = new C(''); // ok class C2 { @@ -25,7 +25,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var c4 = new C2(''); // ok var c5 = new C2(1); // ok @@ -33,7 +33,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new D(1); // ok var d3 = new D(''); // ok } @@ -45,7 +45,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var c2 = new C(''); // ok class C2 { @@ -56,7 +56,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. var c4 = new C2(''); // ok var c5 = new C2(1, 2); // ok @@ -64,7 +64,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. var d2 = new D(1); // ok var d3 = new D(''); // ok } \ No newline at end of file diff --git a/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt b/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt index 8fd3a8412c0..4064a1a11e3 100644 --- a/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt +++ b/tests/baselines/reference/classWithoutExplicitConstructor.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(7,10): error TS2553: Expected 0 arguments, but got 1. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(15,10): error TS2553: Expected 0 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(7,10): error TS2554: Expected 0 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts(15,10): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/classWithoutExplicitConstructor.ts (2 errors) ==== @@ -11,7 +11,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/cl var c = new C(); var c2 = new C(null); // error ~~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. class D { x = 2 @@ -21,4 +21,4 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/cl var d = new D(); var d2 = new D(null); // error ~~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. \ No newline at end of file +!!! error TS2554: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/cloduleTest2.errors.txt b/tests/baselines/reference/cloduleTest2.errors.txt index f8eb1547679..6a3c763ee58 100644 --- a/tests/baselines/reference/cloduleTest2.errors.txt +++ b/tests/baselines/reference/cloduleTest2.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/cloduleTest2.ts(4,13): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/cloduleTest2.ts(10,13): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(4,13): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(10,13): error TS2554: Expected 1 arguments, but got 0. tests/cases/compiler/cloduleTest2.ts(18,7): error TS2339: Property 'bar' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(19,7): error TS2339: Property 'y' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(27,7): error TS2339: Property 'bar' does not exist on type 'm3d'. tests/cases/compiler/cloduleTest2.ts(28,7): error TS2339: Property 'y' does not exist on type 'm3d'. -tests/cases/compiler/cloduleTest2.ts(33,9): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/cloduleTest2.ts(36,10): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(33,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/cloduleTest2.ts(36,10): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/cloduleTest2.ts (8 errors) ==== @@ -14,7 +14,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2553: Expected 1 arguments, declare class m3d { constructor(foo); foo(): void ; static bar(); } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. } module T2 { @@ -22,7 +22,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2553: Expected 1 arguments, module m3d { export var y = 2; } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. } module T3 { @@ -55,9 +55,9 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2553: Expected 1 arguments, declare class m3d { constructor(foo); foo(): void; static bar(); } var r = new m3d(); // error ~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. declare class m4d extends m3d { } var r2 = new m4d(); // error ~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt index 9de8fb36b26..f149bce5080 100644 --- a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt +++ b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(1,7): error TS2506: 'S18' is referenced directly or indirectly in its own base expression. -tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts (2 errors) ==== @@ -10,5 +10,5 @@ tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): erro } (new S18(123)).S18 = 0; ~~~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt index d36448773bd..265ce4686db 100644 --- a/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt +++ b/tests/baselines/reference/constructorInvocationWithTooFewTypeArgs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS2558: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts (1 errors) ==== @@ -12,5 +12,5 @@ tests/cases/compiler/constructorInvocationWithTooFewTypeArgs.ts(9,9): error TS25 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt b/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt index 429d27fd004..c351245ef11 100644 --- a/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt +++ b/tests/baselines/reference/couldNotSelectGenericOverload.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/couldNotSelectGenericOverload.ts(3,11): error TS2553: Expected 1 arguments, but got 2. -tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/couldNotSelectGenericOverload.ts(3,11): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2554: Expected 1 arguments, but got 2. ==== tests/cases/compiler/couldNotSelectGenericOverload.ts (2 errors) ==== @@ -7,11 +7,11 @@ tests/cases/compiler/couldNotSelectGenericOverload.ts(7,11): error TS2553: Expec var b = [1, ""]; var b1G = makeArray(1, ""); // any, no error ~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. var b2G = makeArray(b); // any[] function makeArray2(items: any[]): any[] { return items; } var b3G = makeArray2(1, ""); // error ~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt index 1fcf6e565ca..b8fa513e289 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(11,9): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(24,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(11,9): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts(24,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts (2 errors) ==== @@ -15,7 +15,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var r2 = new Derived(1); class Base2 { @@ -30,5 +30,5 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new D(new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt index d89786b71bf..0bf92d51f93 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(13,9): error TS2553: Expected 1-3 arguments, but got 0. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(30,9): error TS2553: Expected 1-3 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(13,9): error TS2554: Expected 1-3 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts(30,9): error TS2554: Expected 1-3 arguments, but got 0. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts (2 errors) ==== @@ -17,7 +17,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 0. +!!! error TS2554: Expected 1-3 arguments, but got 0. var r2 = new Derived(1); var r3 = new Derived(1, 2); var r4 = new Derived(1, 2, 3); @@ -36,7 +36,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 0. +!!! error TS2554: Expected 1-3 arguments, but got 0. var d2 = new D(new Date()); // ok var d3 = new D(new Date(), new Date()); var d4 = new D(new Date(), new Date(), new Date()); \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt index e447540f853..79b8cd23606 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(21,9): error TS2553: Expected 2 arguments, but got 0. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(22,10): error TS2553: Expected 2 arguments, but got 1. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(44,9): error TS2553: Expected 2 arguments, but got 0. -tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(45,10): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(21,9): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(22,10): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(44,9): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts(45,10): error TS2554: Expected 2 arguments, but got 1. ==== tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts (4 errors) ==== @@ -27,10 +27,10 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 0. +!!! error TS2554: Expected 2 arguments, but got 0. var r2 = new Derived2(1); // error ~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. var r3 = new Derived('', ''); class Base2 { @@ -54,8 +54,8 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D2(); // error ~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 0. +!!! error TS2554: Expected 2 arguments, but got 0. var d2 = new D2(new Date()); // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. var d3 = new D2(new Date(), new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt index de1fa1b36c7..ba1b05944fd 100644 --- a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt +++ b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts (1 errors) ==== @@ -16,4 +16,4 @@ tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): erro var y: MyClass = new MyClass(); y.myMethod(); // error ~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTypeArgumentList.errors.txt b/tests/baselines/reference/emptyTypeArgumentList.errors.txt index c9d041ba31e..036f307447b 100644 --- a/tests/baselines/reference/emptyTypeArgumentList.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentList.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2557: Expected 1 type arguments, but got 0. +tests/cases/compiler/emptyTypeArgumentList.ts(2,1): error TS2558: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentList.ts(2,4): error TS1099: Type argument function foo() { } foo<>(); ~~~~~~~ -!!! error TS2557: Expected 1 type arguments, but got 0. +!!! error TS2558: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt index 88d0981babb..648aa7c6c50 100644 --- a/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt +++ b/tests/baselines/reference/emptyTypeArgumentListWithNew.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2557: Expected 1 type arguments, but got 0. +tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,1): error TS2558: Expected 1 type arguments, but got 0. tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type argument list cannot be empty. @@ -6,6 +6,6 @@ tests/cases/compiler/emptyTypeArgumentListWithNew.ts(2,8): error TS1099: Type ar class foo { } new foo<>(); ~~~~~~~~~~~ -!!! error TS2557: Expected 1 type arguments, but got 0. +!!! error TS2558: Expected 1 type arguments, but got 0. ~~ !!! error TS1099: Type argument list cannot be empty. \ No newline at end of file diff --git a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt index acfa0d0b028..27e8791f5d2 100644 --- a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt +++ b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts (1 errors) ==== @@ -7,7 +7,7 @@ tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error T function f() { var d1 = new derived(); ~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var d2 = new derived(4); } diff --git a/tests/baselines/reference/functionCall11.errors.txt b/tests/baselines/reference/functionCall11.errors.txt index 4425bc6fbfa..e7dc72b1488 100644 --- a/tests/baselines/reference/functionCall11.errors.txt +++ b/tests/baselines/reference/functionCall11.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/functionCall11.ts(4,1): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/compiler/functionCall11.ts(4,1): error TS2554: Expected 1-2 arguments, but got 0. tests/cases/compiler/functionCall11.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall11.ts(6,1): error TS2553: Expected 1-2 arguments, but got 3. +tests/cases/compiler/functionCall11.ts(6,1): error TS2554: Expected 1-2 arguments, but got 3. ==== tests/cases/compiler/functionCall11.ts (3 errors) ==== @@ -9,11 +9,11 @@ tests/cases/compiler/functionCall11.ts(6,1): error TS2553: Expected 1-2 argument foo('foo'); foo(); ~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. foo('foo', 1, 'bar'); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 3. +!!! error TS2554: Expected 1-2 arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall12.errors.txt b/tests/baselines/reference/functionCall12.errors.txt index 09adbf933dc..3c22d0dcef7 100644 --- a/tests/baselines/reference/functionCall12.errors.txt +++ b/tests/baselines/reference/functionCall12.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall12.ts(4,1): error TS2553: Expected 1-3 arguments, but got 0. +tests/cases/compiler/functionCall12.ts(4,1): error TS2554: Expected 1-3 arguments, but got 0. tests/cases/compiler/functionCall12.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. @@ -9,7 +9,7 @@ tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type '3' foo('foo'); foo(); ~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 0. +!!! error TS2554: Expected 1-3 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall13.errors.txt b/tests/baselines/reference/functionCall13.errors.txt index 9549ac36648..c53f63b7d78 100644 --- a/tests/baselines/reference/functionCall13.errors.txt +++ b/tests/baselines/reference/functionCall13.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall13.ts(4,1): error TS2554: Expected at least 1 arguments, but got 0. +tests/cases/compiler/functionCall13.ts(4,1): error TS2555: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -8,7 +8,7 @@ tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2554: Expected at least 1 arguments, but got 0. +!!! error TS2555: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall16.errors.txt b/tests/baselines/reference/functionCall16.errors.txt index d77f2f996db..b3345d82779 100644 --- a/tests/baselines/reference/functionCall16.errors.txt +++ b/tests/baselines/reference/functionCall16.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall16.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall16.ts(5,1): error TS2554: Expected at least 1 arguments, but got 0. +tests/cases/compiler/functionCall16.ts(5,1): error TS2555: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' foo('foo', 'bar'); foo(); ~~~~~ -!!! error TS2554: Expected at least 1 arguments, but got 0. +!!! error TS2555: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall17.errors.txt b/tests/baselines/reference/functionCall17.errors.txt index 77184809b80..c672c092677 100644 --- a/tests/baselines/reference/functionCall17.errors.txt +++ b/tests/baselines/reference/functionCall17.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall17.ts(2,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall17.ts(4,1): error TS2554: Expected at least 1 arguments, but got 0. +tests/cases/compiler/functionCall17.ts(4,1): error TS2555: Expected at least 1 arguments, but got 0. tests/cases/compiler/functionCall17.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. @@ -12,7 +12,7 @@ tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' foo('foo'); foo(); ~~~~~ -!!! error TS2554: Expected at least 1 arguments, but got 0. +!!! error TS2555: Expected at least 1 arguments, but got 0. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall6.errors.txt b/tests/baselines/reference/functionCall6.errors.txt index baaca457054..5200a5a3e6f 100644 --- a/tests/baselines/reference/functionCall6.errors.txt +++ b/tests/baselines/reference/functionCall6.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/functionCall6.ts(3,5): error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. -tests/cases/compiler/functionCall6.ts(4,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/compiler/functionCall6.ts(5,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/functionCall6.ts(4,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/functionCall6.ts(5,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionCall6.ts (3 errors) ==== @@ -11,8 +11,8 @@ tests/cases/compiler/functionCall6.ts(5,1): error TS2553: Expected 1 arguments, !!! error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. foo('foo', 'bar'); ~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. foo(); ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall7.errors.txt b/tests/baselines/reference/functionCall7.errors.txt index aaa59ab5e1f..78f2a3384db 100644 --- a/tests/baselines/reference/functionCall7.errors.txt +++ b/tests/baselines/reference/functionCall7.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/functionCall7.ts(5,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/functionCall7.ts(5,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/compiler/functionCall7.ts(6,5): error TS2345: Argument of type '4' is not assignable to parameter of type 'c1'. -tests/cases/compiler/functionCall7.ts(7,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/functionCall7.ts(7,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionCall7.ts (3 errors) ==== @@ -10,11 +10,11 @@ tests/cases/compiler/functionCall7.ts(7,1): error TS2553: Expected 1 arguments, foo(myC); foo(myC, myC); ~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. foo(4); ~ !!! error TS2345: Argument of type '4' is not assignable to parameter of type 'c1'. foo(); ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall8.errors.txt b/tests/baselines/reference/functionCall8.errors.txt index cdb2ebc44cf..86e01baa740 100644 --- a/tests/baselines/reference/functionCall8.errors.txt +++ b/tests/baselines/reference/functionCall8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionCall8.ts(3,1): error TS2553: Expected 0-1 arguments, but got 2. +tests/cases/compiler/functionCall8.ts(3,1): error TS2554: Expected 0-1 arguments, but got 2. tests/cases/compiler/functionCall8.ts(4,5): error TS2345: Argument of type '4' is not assignable to parameter of type 'string'. @@ -7,7 +7,7 @@ tests/cases/compiler/functionCall8.ts(4,5): error TS2345: Argument of type '4' i foo('foo'); foo('foo', 'bar'); ~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 0-1 arguments, but got 2. +!!! error TS2554: Expected 0-1 arguments, but got 2. foo(4); ~ !!! error TS2345: Argument of type '4' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall9.errors.txt b/tests/baselines/reference/functionCall9.errors.txt index aebd6cc5235..50c33a15aad 100644 --- a/tests/baselines/reference/functionCall9.errors.txt +++ b/tests/baselines/reference/functionCall9.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/functionCall9.ts(4,11): error TS2345: Argument of type '"bar"' is not assignable to parameter of type 'number'. -tests/cases/compiler/functionCall9.ts(5,1): error TS2553: Expected 0-2 arguments, but got 3. +tests/cases/compiler/functionCall9.ts(5,1): error TS2554: Expected 0-2 arguments, but got 3. ==== tests/cases/compiler/functionCall9.ts (2 errors) ==== @@ -11,5 +11,5 @@ tests/cases/compiler/functionCall9.ts(5,1): error TS2553: Expected 0-2 arguments !!! error TS2345: Argument of type '"bar"' is not assignable to parameter of type 'number'. foo('foo', 1, 'bar'); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 0-2 arguments, but got 3. +!!! error TS2554: Expected 0-2 arguments, but got 3. foo(); \ No newline at end of file diff --git a/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt b/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt index e770eb5932b..f87312634f8 100644 --- a/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt +++ b/tests/baselines/reference/functionConstraintSatisfaction2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(5,5): error TS2345: Argument of type '1' is not assignable to parameter of type 'Function'. -tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(6,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(7,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(6,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(7,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(23,14): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(x: string) => string'. Type 'Function' provides no match for the signature '(x: string): string'. tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstraintSatisfaction2.ts(24,15): error TS2345: Argument of type '(x: string[]) => string[]' is not assignable to parameter of type '(x: string) => string'. @@ -36,10 +36,10 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/functionConstrain !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'Function'. foo(() => { }, 1); ~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. foo(1, () => { }); ~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. function foo2 string>(x: T): T { return x; } diff --git a/tests/baselines/reference/functionOverloads29.errors.txt b/tests/baselines/reference/functionOverloads29.errors.txt index 327eba07aba..2423f53165f 100644 --- a/tests/baselines/reference/functionOverloads29.errors.txt +++ b/tests/baselines/reference/functionOverloads29.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads29.ts(4,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/functionOverloads29.ts(4,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads29.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads29.ts(4,9): error TS2553: Expected 1 argum function foo(bar:any):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads34.errors.txt b/tests/baselines/reference/functionOverloads34.errors.txt index 6c7d1085981..c47eabef592 100644 --- a/tests/baselines/reference/functionOverloads34.errors.txt +++ b/tests/baselines/reference/functionOverloads34.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads34.ts(4,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/functionOverloads34.ts(4,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads34.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads34.ts(4,9): error TS2553: Expected 1 argum function foo(bar:{a:any;}):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads37.errors.txt b/tests/baselines/reference/functionOverloads37.errors.txt index 1a7ed43a8c2..523c4912e80 100644 --- a/tests/baselines/reference/functionOverloads37.errors.txt +++ b/tests/baselines/reference/functionOverloads37.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionOverloads37.ts(4,9): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/functionOverloads37.ts(4,9): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/functionOverloads37.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/functionOverloads37.ts(4,9): error TS2553: Expected 1 argum function foo(bar:{a:any;}[]):any{ return bar } var x = foo(); ~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt index 74450aba3b5..7ff051bd63e 100644 --- a/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt +++ b/tests/baselines/reference/genericCallbackInvokedInsideItsContainingFunction1.errors.txt @@ -1,33 +1,33 @@ -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(2,14): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(3,16): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(4,14): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(8,15): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(9,15): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(12,17): error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(13,15): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts (8 errors) ==== function foo(x:T, y:U, f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r4 = f(null); var r11 = f(x); var r21 = f(x); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r31 = f(null); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r41 = f(null); var r12 = f(y); @@ -35,9 +35,9 @@ tests/cases/compiler/genericCallbackInvokedInsideItsContainingFunction1.ts(14,15 !!! error TS2345: Argument of type 'U' is not assignable to parameter of type 'T'. var r22 = f(y); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r32 = f(null); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r42 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/genericDefaultsErrors.errors.txt b/tests/baselines/reference/genericDefaultsErrors.errors.txt index 9067eb5d89d..6200046c49f 100644 --- a/tests/baselines/reference/genericDefaultsErrors.errors.txt +++ b/tests/baselines/reference/genericDefaultsErrors.errors.txt @@ -3,8 +3,8 @@ tests/cases/compiler/genericDefaultsErrors.ts(4,59): error TS2344: Type 'T' does Type 'string' is not assignable to type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(5,44): error TS2344: Type 'T' does not satisfy the constraint 'number'. tests/cases/compiler/genericDefaultsErrors.ts(6,39): error TS2344: Type 'number' does not satisfy the constraint 'T'. -tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2557: Expected 2-3 type arguments, but got 1. -tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2557: Expected 2-3 type arguments, but got 4. +tests/cases/compiler/genericDefaultsErrors.ts(10,1): error TS2558: Expected 2-3 type arguments, but got 1. +tests/cases/compiler/genericDefaultsErrors.ts(13,1): error TS2558: Expected 2-3 type arguments, but got 4. tests/cases/compiler/genericDefaultsErrors.ts(17,13): error TS2345: Argument of type '"a"' is not assignable to parameter of type 'number'. tests/cases/compiler/genericDefaultsErrors.ts(19,11): error TS2428: All declarations of 'i00' must have identical type parameters. tests/cases/compiler/genericDefaultsErrors.ts(20,11): error TS2428: All declarations of 'i00' must have identical type parameters. @@ -44,12 +44,12 @@ tests/cases/compiler/genericDefaultsErrors.ts(38,20): error TS4033: Property 'x' f11(); // ok f11<1>(); // error ~~~~~~~~ -!!! error TS2557: Expected 2-3 type arguments, but got 1. +!!! error TS2558: Expected 2-3 type arguments, but got 1. f11<1, 2>(); // ok f11<1, 2, 3>(); // ok f11<1, 2, 3, 4>(); // error ~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2-3 type arguments, but got 4. +!!! error TS2558: Expected 2-3 type arguments, but got 4. declare function f12(a?: U): void; f12(); // ok diff --git a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt index 02946e0d0bd..d7dfc18d40f 100644 --- a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt +++ b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS2553: Expected 1-3 arguments, but got 0. +tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS2554: Expected 1-3 arguments, but got 0. ==== tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts (1 errors) ==== @@ -10,7 +10,7 @@ tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS25 utils.fold(); // error ~~~~~~~~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 0. +!!! error TS2554: Expected 1-3 arguments, but got 0. utils.fold(null); // no error utils.fold(null, null); // no error utils.fold(null, null, null); // error: Unable to invoke type with no call signatures diff --git a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt index 12fff1ff40e..9f8694d2fca 100644 --- a/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt +++ b/tests/baselines/reference/genericWithOpenTypeParameters1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(7,40): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(8,35): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/genericWithOpenTypeParameters1.ts (3 errors) ==== @@ -15,9 +15,9 @@ tests/cases/compiler/genericWithOpenTypeParameters1.ts(9,35): error TS2557: Expe !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var f2 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var f3 = (x: B) => { return x.foo(1); } // error ~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var f4 = (x: B) => { return x.foo(1); } // no error \ No newline at end of file diff --git a/tests/baselines/reference/grammarAmbiguities.errors.txt b/tests/baselines/reference/grammarAmbiguities.errors.txt index 17861e6fc95..d3d0637bd2c 100644 --- a/tests/baselines/reference/grammarAmbiguities.errors.txt +++ b/tests/baselines/reference/grammarAmbiguities.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(8,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(8,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): error TS2554: Expected 1 arguments, but got 2. ==== tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts (2 errors) ==== @@ -12,9 +12,9 @@ tests/cases/conformance/expressions/functionCalls/grammarAmbiguities.ts(9,1): er f(g(7)); f(g < A, B > 7); // Should error ~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. f(g < A, B > +(7)); // Should error ~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. \ No newline at end of file diff --git a/tests/baselines/reference/grammarAmbiguities1.errors.txt b/tests/baselines/reference/grammarAmbiguities1.errors.txt index 1d206b4209d..22467d7ee77 100644 --- a/tests/baselines/reference/grammarAmbiguities1.errors.txt +++ b/tests/baselines/reference/grammarAmbiguities1.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/grammarAmbiguities1.ts(8,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/grammarAmbiguities1.ts(8,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/compiler/grammarAmbiguities1.ts(8,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. tests/cases/compiler/grammarAmbiguities1.ts(8,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. -tests/cases/compiler/grammarAmbiguities1.ts(9,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/compiler/grammarAmbiguities1.ts(9,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/compiler/grammarAmbiguities1.ts(9,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. @@ -16,14 +16,14 @@ tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' ca f(g(7)); f(g < A, B > 7); ~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. ~~~~~ !!! error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. ~~~~~ !!! error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. f(g < A, B > +(7)); ~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. ~~~~~ !!! error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. ~~~~~~~~ diff --git a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt index 77de65db461..05cc1ee1cd0 100644 --- a/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateGenericClassWithWrongNumberOfTypeArguments.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2557: Expected 1 type arguments, but got 2. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(8,9): error TS2558: Expected 1 type arguments, but got 2. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts(16,9): error TS2558: Expected 2 type arguments, but got 1. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGenericClassWithWrongNumberOfTypeArguments.ts (2 errors) ==== @@ -12,7 +12,7 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri var c = new C(); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 1 type arguments, but got 2. +!!! error TS2558: Expected 1 type arguments, but got 2. class D { x: T @@ -22,4 +22,4 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateGeneri // BUG 794238 var d = new D(); ~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. \ No newline at end of file +!!! error TS2558: Expected 2 type arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt index 5ce7cede0d0..196af18aa9a 100644 --- a/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt +++ b/tests/baselines/reference/instantiateNonGenericTypeWithTypeArguments.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(8,9): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(11,9): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(14,10): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGenericTypeWithTypeArguments.ts(18,10): error TS2347: Untyped function calls may not accept type arguments. @@ -16,21 +16,21 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/instantiateNonGen var c = new C(); ~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. function Foo(): void { } var r = new Foo(); ~~~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var f: { (): void }; var r2 = new f(); ~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var a: any; // BUG 790977 diff --git a/tests/baselines/reference/iteratorSpreadInCall.errors.txt b/tests/baselines/reference/iteratorSpreadInCall.errors.txt index d44fa5c3e2e..1831013b6e7 100644 --- a/tests/baselines/reference/iteratorSpreadInCall.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2555: Expected 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2556: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2555: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2555: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt index 8bdefd6732d..0d10c9f25e5 100644 --- a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2555: Expected 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2556: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2555 foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2555: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt index d36e95df24c..03cc296b8ab 100644 --- a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2555: Expected 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2556: Expected 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2555: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2555: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt index 81fe5c9a271..899ac1d9e90 100644 --- a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2556: Expected at least 1 arguments, but got a minimum of 0. +tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2557: Expected at least 1 arguments, but got a minimum of 0. ==== tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts (1 errors) ==== @@ -18,4 +18,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2556: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2556: Expected at least 1 arguments, but got a minimum of 0. \ No newline at end of file +!!! error TS2557: Expected at least 1 arguments, but got a minimum of 0. \ No newline at end of file diff --git a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt index 30b10dc4ef2..5a308a61b0f 100644 --- a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt +++ b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/bar.ts(1,1): error TS2553: Expected 3 arguments, but got 0. -tests/cases/compiler/bar.ts(2,1): error TS2553: Expected 3 arguments, but got 1. -tests/cases/compiler/bar.ts(3,1): error TS2553: Expected 3 arguments, but got 2. +tests/cases/compiler/bar.ts(1,1): error TS2554: Expected 3 arguments, but got 0. +tests/cases/compiler/bar.ts(2,1): error TS2554: Expected 3 arguments, but got 1. +tests/cases/compiler/bar.ts(3,1): error TS2554: Expected 3 arguments, but got 2. ==== tests/cases/compiler/foo.js (0 errors) ==== @@ -15,13 +15,13 @@ tests/cases/compiler/bar.ts(3,1): error TS2553: Expected 3 arguments, but got 2. ==== tests/cases/compiler/bar.ts (3 errors) ==== f(); // Error ~~~ -!!! error TS2553: Expected 3 arguments, but got 0. +!!! error TS2554: Expected 3 arguments, but got 0. f(1); // Error ~~~~ -!!! error TS2553: Expected 3 arguments, but got 1. +!!! error TS2554: Expected 3 arguments, but got 1. f(1, 2); // Error ~~~~~~~ -!!! error TS2553: Expected 3 arguments, but got 2. +!!! error TS2554: Expected 3 arguments, but got 2. f(1, 2, 3); // OK \ No newline at end of file diff --git a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt index 7c4c287f179..9b95b143d64 100644 --- a/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt +++ b/tests/baselines/reference/mismatchedExplicitTypeParameterAndArgumentType.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(10,30): error TS2345: Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2557: Expected 2 type arguments, but got 1. +tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): error TS2558: Expected 2 type arguments, but got 1. ==== tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts (2 errors) ==== @@ -21,5 +21,5 @@ tests/cases/compiler/mismatchedExplicitTypeParameterAndArgumentType.ts(11,11): e !!! error TS2345: Type 'string' is not assignable to type 'number'. var r7b = map([1, ""], (x) => x.toString()); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 2 type arguments, but got 1. +!!! error TS2558: Expected 2 type arguments, but got 1. var r8 = map([1, ""], (x) => x.toString()); \ No newline at end of file diff --git a/tests/baselines/reference/optionalParamArgsTest.errors.txt b/tests/baselines/reference/optionalParamArgsTest.errors.txt index d16009c2b9d..7a3e044e6fd 100644 --- a/tests/baselines/reference/optionalParamArgsTest.errors.txt +++ b/tests/baselines/reference/optionalParamArgsTest.errors.txt @@ -1,25 +1,25 @@ tests/cases/compiler/optionalParamArgsTest.ts(31,12): error TS2393: Duplicate function implementation. tests/cases/compiler/optionalParamArgsTest.ts(34,12): error TS2393: Duplicate function implementation. -tests/cases/compiler/optionalParamArgsTest.ts(98,1): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/optionalParamArgsTest.ts(99,1): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/optionalParamArgsTest.ts(100,1): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/optionalParamArgsTest.ts(101,1): error TS2553: Expected 0 arguments, but got 1. -tests/cases/compiler/optionalParamArgsTest.ts(102,1): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/optionalParamArgsTest.ts(103,1): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/optionalParamArgsTest.ts(104,1): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/optionalParamArgsTest.ts(105,1): error TS2553: Expected 1 arguments, but got 0. -tests/cases/compiler/optionalParamArgsTest.ts(106,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/compiler/optionalParamArgsTest.ts(107,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/compiler/optionalParamArgsTest.ts(108,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/compiler/optionalParamArgsTest.ts(109,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/compiler/optionalParamArgsTest.ts(110,1): error TS2553: Expected 0-2 arguments, but got 3. -tests/cases/compiler/optionalParamArgsTest.ts(111,1): error TS2553: Expected 0-2 arguments, but got 3. -tests/cases/compiler/optionalParamArgsTest.ts(112,1): error TS2553: Expected 0-2 arguments, but got 3. -tests/cases/compiler/optionalParamArgsTest.ts(113,1): error TS2553: Expected 0-2 arguments, but got 3. -tests/cases/compiler/optionalParamArgsTest.ts(114,1): error TS2553: Expected 1-2 arguments, but got 0. -tests/cases/compiler/optionalParamArgsTest.ts(115,1): error TS2553: Expected 1-2 arguments, but got 0. -tests/cases/compiler/optionalParamArgsTest.ts(116,1): error TS2553: Expected 1-2 arguments, but got 0. -tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(98,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(99,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(100,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(101,1): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/optionalParamArgsTest.ts(102,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(103,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(104,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(105,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(106,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(107,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(108,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(109,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/compiler/optionalParamArgsTest.ts(110,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(111,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(112,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(113,1): error TS2554: Expected 0-2 arguments, but got 3. +tests/cases/compiler/optionalParamArgsTest.ts(114,1): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(115,1): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(116,1): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2554: Expected 1-2 arguments, but got 0. ==== tests/cases/compiler/optionalParamArgsTest.ts (22 errors) ==== @@ -126,64 +126,64 @@ tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2553: Expected 1-2 // Negative tests - we expect these cases to fail c1o1.C1M1(1); ~~~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. i1o1.C1M1(1); ~~~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. F1(1); ~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. L1(1); ~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. c1o1.C1M2(); ~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. i1o1.C1M2(); ~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. F2(); ~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. L2(); ~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. c1o1.C1M2(1,2); ~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. i1o1.C1M2(1,2); ~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. F2(1,2); ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. L2(1,2); ~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. c1o1.C1M3(1,2,3); ~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 0-2 arguments, but got 3. +!!! error TS2554: Expected 0-2 arguments, but got 3. i1o1.C1M3(1,2,3); ~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 0-2 arguments, but got 3. +!!! error TS2554: Expected 0-2 arguments, but got 3. F3(1,2,3); ~~~~~~~~~ -!!! error TS2553: Expected 0-2 arguments, but got 3. +!!! error TS2554: Expected 0-2 arguments, but got 3. L3(1,2,3); ~~~~~~~~~ -!!! error TS2553: Expected 0-2 arguments, but got 3. +!!! error TS2554: Expected 0-2 arguments, but got 3. c1o1.C1M4(); ~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. i1o1.C1M4(); ~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. F4(); ~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. L4(); ~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. function fnOpt1(id: number, children: number[] = [], expectedPath: number[] = [], isRoot?: boolean): void {} function fnOpt2(id: number, children?: number[], expectedPath?: number[], isRoot?: boolean): void {} diff --git a/tests/baselines/reference/overload1.errors.txt b/tests/baselines/reference/overload1.errors.txt index 100c92d4002..2f118e59f64 100644 --- a/tests/baselines/reference/overload1.errors.txt +++ b/tests/baselines/reference/overload1.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/overload1.ts(27,5): error TS2322: Type 'C' is not assignable to type 'string'. tests/cases/compiler/overload1.ts(29,1): error TS2322: Type 'number' is not assignable to type 'string'. -tests/cases/compiler/overload1.ts(31,3): error TS2553: Expected 1-2 arguments, but got 3. -tests/cases/compiler/overload1.ts(32,3): error TS2553: Expected 1-2 arguments, but got 0. +tests/cases/compiler/overload1.ts(31,3): error TS2554: Expected 1-2 arguments, but got 3. +tests/cases/compiler/overload1.ts(32,3): error TS2554: Expected 1-2 arguments, but got 0. tests/cases/compiler/overload1.ts(33,1): error TS2322: Type 'C' is not assignable to type 'string'. tests/cases/compiler/overload1.ts(34,9): error TS2345: Argument of type '2' is not assignable to parameter of type 'string'. @@ -43,10 +43,10 @@ tests/cases/compiler/overload1.ts(34,9): error TS2345: Argument of type '2' is n var z:string=x.g(x.g(3,3)); // good z=x.g(2,2,2); // no match ~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 3. +!!! error TS2554: Expected 1-2 arguments, but got 3. z=x.g(); // no match ~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. z=x.g(new O.B()); // ambiguous (up and down conversion) ~ !!! error TS2322: Type 'C' is not assignable to type 'string'. diff --git a/tests/baselines/reference/overloadResolution.errors.txt b/tests/baselines/reference/overloadResolution.errors.txt index a924826a6a0..37cea935e66 100644 --- a/tests/baselines/reference/overloadResolution.errors.txt +++ b/tests/baselines/reference/overloadResolution.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(27,5): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(41,11): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2557: Expected 1-3 type arguments, but got 4. +tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(63,1): error TS2558: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(70,21): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(71,21): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(81,5): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -79,7 +79,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolution.ts(91,22): // Generic overloads with differing arity called with type argument count that doesn't match any overload fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 1-3 type arguments, but got 4. +!!! error TS2558: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints function fn4(n: T, m: U); diff --git a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt index 9306fa8e1a2..92f3a7cfa90 100644 --- a/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionClassConstructors.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2557: Expected 3 type arguments, but got 1. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2557: Expected 3 type arguments, but got 2. -tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2557: Expected 3 type arguments, but got 4. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(60,1): error TS2558: Expected 3 type arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(61,1): error TS2558: Expected 3 type arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(65,1): error TS2558: Expected 3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(73,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(74,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstructors.ts(75,9): error TS2344: Type 'number' does not satisfy the constraint 'string'. @@ -78,16 +78,16 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionClassConstru // Generic overloads with differing arity called with type arguments matching each overload type parameter count new fn3(4); // Error ~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 3 type arguments, but got 1. +!!! error TS2558: Expected 3 type arguments, but got 1. new fn3('', '', ''); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 3 type arguments, but got 2. +!!! error TS2558: Expected 3 type arguments, but got 2. new fn3('', '', 3); // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 3 type arguments, but got 4. +!!! error TS2558: Expected 3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints class fn4 { diff --git a/tests/baselines/reference/overloadResolutionConstructors.errors.txt b/tests/baselines/reference/overloadResolutionConstructors.errors.txt index f0008553f2e..9b09992228e 100644 --- a/tests/baselines/reference/overloadResolutionConstructors.errors.txt +++ b/tests/baselines/reference/overloadResolutionConstructors.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(27,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(43,15): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2557: Expected 1-3 type arguments, but got 4. +tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(67,1): error TS2558: Expected 1-3 type arguments, but got 4. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(77,25): error TS2345: Argument of type '3' is not assignable to parameter of type 'string'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(78,25): error TS2345: Argument of type '""' is not assignable to parameter of type 'number'. tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors.ts(88,9): error TS2344: Type 'boolean' does not satisfy the constraint 'number'. @@ -83,7 +83,7 @@ tests/cases/conformance/expressions/functionCalls/overloadResolutionConstructors // Generic overloads with differing arity called with type argument count that doesn't match any overload new fn3(); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 1-3 type arguments, but got 4. +!!! error TS2558: Expected 1-3 type arguments, but got 4. // Generic overloads with constraints called with type arguments that satisfy the constraints interface fn4 { diff --git a/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt b/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt index c106c3b64ac..bdbc2310fb1 100644 --- a/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt +++ b/tests/baselines/reference/overloadResolutionOnDefaultConstructor1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2553: Expected 0 arguments, but got 1. +tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2554: Expected 0 arguments, but got 1. ==== tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts (1 errors) ==== @@ -6,6 +6,6 @@ tests/cases/compiler/overloadResolutionOnDefaultConstructor1.ts(3,16): error TS2 public clone() { return new Bar(0); ~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. } } \ No newline at end of file diff --git a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt index d79421264d4..52bcaaf790b 100644 --- a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt +++ b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2557: Expected 0-2 type arguments, but got 3. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(5,1): error TS2558: Expected 0-2 type arguments, but got 3. tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2350: Only a void function can be called with the 'new' keyword. -tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2557: Expected 0-2 type arguments, but got 3. +tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2558: Expected 0-2 type arguments, but got 3. ==== tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts (3 errors) ==== @@ -10,9 +10,9 @@ tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(6,1): error TS2557: Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0-2 type arguments, but got 3. +!!! error TS2558: Expected 0-2 type arguments, but got 3. new Callbacks('s'); // wrong number of type arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2350: Only a void function can be called with the 'new' keyword. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0-2 type arguments, but got 3. \ No newline at end of file +!!! error TS2558: Expected 0-2 type arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt index 5ac1a1003ba..c13916fa39d 100644 --- a/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt +++ b/tests/baselines/reference/parserConstructorAmbiguity3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,1): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,10): error TS2304: Cannot find name 'A'. tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts(1,12): error TS1005: '(' expected. @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserConstructorAmbiguity3.ts (3 errors) ==== new Date ~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. ~ !!! error TS2304: Cannot find name 'A'. diff --git a/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt b/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt index e03ef38b1ac..36bd5b08e19 100644 --- a/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt +++ b/tests/baselines/reference/parserNoASIOnCallAfterFunctionExpression1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(1,9): error TS2553: Expected 0 arguments, but got 1. +tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(1,9): error TS2554: Expected 0 arguments, but got 1. tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpression1.ts(2,7): error TS2304: Cannot find name 'window'. @@ -7,7 +7,7 @@ tests/cases/conformance/parser/ecmascript5/parserNoASIOnCallAfterFunctionExpress ~~~~~~~~~~~~~~~ (window).foo; ~~~~~~~~~~~~~ -!!! error TS2553: Expected 0 arguments, but got 1. +!!! error TS2554: Expected 0 arguments, but got 1. ~~~~~~ !!! error TS2304: Cannot find name 'window'. \ No newline at end of file diff --git a/tests/baselines/reference/recursiveFunctionTypes.errors.txt b/tests/baselines/reference/recursiveFunctionTypes.errors.txt index 72dd792765f..77010d7efa1 100644 --- a/tests/baselines/reference/recursiveFunctionTypes.errors.txt +++ b/tests/baselines/reference/recursiveFunctionTypes.errors.txt @@ -8,9 +8,9 @@ tests/cases/compiler/recursiveFunctionTypes.ts(17,5): error TS2322: Type '() => tests/cases/compiler/recursiveFunctionTypes.ts(22,5): error TS2345: Argument of type '3' is not assignable to parameter of type '(t: typeof g) => void'. tests/cases/compiler/recursiveFunctionTypes.ts(25,1): error TS2322: Type '3' is not assignable to type '() => any'. tests/cases/compiler/recursiveFunctionTypes.ts(30,10): error TS2394: Overload signature is not compatible with function implementation. -tests/cases/compiler/recursiveFunctionTypes.ts(33,1): error TS2553: Expected 0-1 arguments, but got 2. +tests/cases/compiler/recursiveFunctionTypes.ts(33,1): error TS2554: Expected 0-1 arguments, but got 2. tests/cases/compiler/recursiveFunctionTypes.ts(34,4): error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f6; (a: typeof f6): () => number; }'. -tests/cases/compiler/recursiveFunctionTypes.ts(42,1): error TS2553: Expected 0-1 arguments, but got 2. +tests/cases/compiler/recursiveFunctionTypes.ts(42,1): error TS2554: Expected 0-1 arguments, but got 2. tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f7; (a: typeof f7): () => number; (a: number): number; (a?: typeof f7): typeof f7; }'. @@ -68,7 +68,7 @@ tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of f6("", 3); // error (arity mismatch) ~~~~~~~~~ -!!! error TS2553: Expected 0-1 arguments, but got 2. +!!! error TS2554: Expected 0-1 arguments, but got 2. f6(""); // ok (function takes an any param) ~~ !!! error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f6; (a: typeof f6): () => number; }'. @@ -81,7 +81,7 @@ tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of f7("", 3); // error (arity mismatch) ~~~~~~~~~ -!!! error TS2553: Expected 0-1 arguments, but got 2. +!!! error TS2554: Expected 0-1 arguments, but got 2. f7(""); // ok (function takes an any param) ~~ !!! error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f7; (a: typeof f7): () => number; (a: number): number; (a?: typeof f7): typeof f7; }'. diff --git a/tests/baselines/reference/requiredInitializedParameter1.errors.txt b/tests/baselines/reference/requiredInitializedParameter1.errors.txt index d227eb1fc6e..31c0f70ee8d 100644 --- a/tests/baselines/reference/requiredInitializedParameter1.errors.txt +++ b/tests/baselines/reference/requiredInitializedParameter1.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/requiredInitializedParameter1.ts(11,1): error TS2553: Expected 3 arguments, but got 2. -tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2553: Expected 3 arguments, but got 1. +tests/cases/compiler/requiredInitializedParameter1.ts(11,1): error TS2554: Expected 3 arguments, but got 2. +tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2554: Expected 3 arguments, but got 1. ==== tests/cases/compiler/requiredInitializedParameter1.ts (2 errors) ==== @@ -15,14 +15,14 @@ tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2553: Expec f1(0, 1); ~~~~~~~~ -!!! error TS2553: Expected 3 arguments, but got 2. +!!! error TS2554: Expected 3 arguments, but got 2. f2(0, 1); f3(0, 1); f4(0, 1); f1(0); ~~~~~ -!!! error TS2553: Expected 3 arguments, but got 1. +!!! error TS2554: Expected 3 arguments, but got 1. f2(0); f3(0); f4(0); \ No newline at end of file diff --git a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt index 3568d92931c..cccbba2f4b5 100644 --- a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt +++ b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2554: Expected at least 1 arguments, but got 0. +tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2555: Expected at least 1 arguments, but got 0. ==== tests/cases/compiler/restParamsWithNonRestParams.ts (1 errors) ==== @@ -7,6 +7,6 @@ tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2554: Expected function foo2(a:string, ...b:number[]){} foo2(); // should be an error ~~~~~~ -!!! error TS2554: Expected at least 1 arguments, but got 0. +!!! error TS2555: Expected at least 1 arguments, but got 0. function foo3(a?:string, ...b:number[]){} foo3(); // error but shouldn't be \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt index d105ea1efec..109312d6264 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.errors.txt @@ -4,9 +4,9 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(11,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(12,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(13,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(14,9): error TS2553: Expected 1-3 arguments, but got 4. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(14,9): error TS2554: Expected 1-3 arguments, but got 4. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(19,20): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(21,9): error TS2553: Expected 1-3 arguments, but got 4. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts(21,9): error TS2554: Expected 1-3 arguments, but got 4. ==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1.ts (8 errors) ==== @@ -36,7 +36,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio !!! error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. var f = foo([], 1, 2, 3); // any (with error) ~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 4. +!!! error TS2554: Expected 1-3 arguments, but got 4. var u = foo ``; // number var v = foo `${1}`; // string @@ -47,5 +47,5 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio var y = foo `${1}${"2"}`; // {} var z = foo `${1}${2}${3}`; // any (with error) ~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 4. +!!! error TS2554: Expected 1-3 arguments, but got 4. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt index 85e6c35ec4b..0d2cafea7b3 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1_ES6.errors.txt @@ -4,9 +4,9 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(11,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(12,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(13,13): error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(14,9): error TS2553: Expected 1-3 arguments, but got 4. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(14,9): error TS2554: Expected 1-3 arguments, but got 4. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(19,20): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(21,9): error TS2553: Expected 1-3 arguments, but got 4. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts(21,9): error TS2554: Expected 1-3 arguments, but got 4. ==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution1_ES6.ts (8 errors) ==== @@ -36,7 +36,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio !!! error TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'TemplateStringsArray'. var f = foo([], 1, 2, 3); // any (with error) ~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 4. +!!! error TS2554: Expected 1-3 arguments, but got 4. var u = foo ``; // number var v = foo `${1}`; // string @@ -47,5 +47,5 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio var y = foo `${1}${"2"}`; // {} var z = foo `${1}${2}${3}`; // any (with error) ~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-3 arguments, but got 4. +!!! error TS2554: Expected 1-3 arguments, but got 4. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt index 169cffd28cc..e7fb6ea1241 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(9,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(18,4): error TS2339: Property 'foo' does not exist on type 'Date'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(44,1): error TS2553: Expected 2-4 arguments, but got 1. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(44,1): error TS2554: Expected 2-4 arguments, but got 1. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(62,9): error TS2345: Argument of type 'true' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(63,18): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts(69,18): error TS2339: Property 'toFixed' does not exist on type 'string'. @@ -56,7 +56,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio // Generic overloads with differing arity tagging with argument count that doesn't match any overload fn3 ``; // Error ~~~~~~ -!!! error TS2553: Expected 2-4 arguments, but got 1. +!!! error TS2554: Expected 2-4 arguments, but got 1. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt index dcbc5e1cd79..d41d64c5a28 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(9,9): error TS2345: Argument of type '{}' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(18,4): error TS2339: Property 'foo' does not exist on type 'Date'. -tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(44,1): error TS2553: Expected 2-4 arguments, but got 1. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(44,1): error TS2554: Expected 2-4 arguments, but got 1. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(62,9): error TS2345: Argument of type 'true' is not assignable to parameter of type 'number'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(63,18): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts(69,18): error TS2339: Property 'toFixed' does not exist on type 'string'. @@ -56,7 +56,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio // Generic overloads with differing arity tagging with argument count that doesn't match any overload fn3 ``; // Error ~~~~~~ -!!! error TS2553: Expected 2-4 arguments, but got 1. +!!! error TS2554: Expected 2-4 arguments, but got 1. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt index 72484f20964..71066aec61f 100644 --- a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt +++ b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,1): error TS2553: Expected 3 arguments, but got 4. +tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,1): error TS2554: Expected 3 arguments, but got 4. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,24): error TS1109: Expression expected. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,28): error TS1109: Expression expected. @@ -10,7 +10,7 @@ tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions4.ts(5,28): // Incomplete call, but too many parameters. f `123qdawdrqw${ 1 }${ }${ ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 3 arguments, but got 4. +!!! error TS2554: Expected 3 arguments, but got 4. ~ !!! error TS1109: Expression expected. diff --git a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt index 8d944e5b1fd..e18bafa9149 100644 --- a/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt +++ b/tests/baselines/reference/taggedTemplatesWithIncompleteTemplateExpressions5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,1): error TS2553: Expected 3 arguments, but got 4. +tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,1): error TS2554: Expected 3 arguments, but got 4. tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,30): error TS1109: Expression expected. @@ -9,6 +9,6 @@ tests/cases/compiler/taggedTemplatesWithIncompleteTemplateExpressions5.ts(5,30): // Incomplete call, but too many parameters. f `123qdawdrqw${ 1 }${ 2 }${ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 3 arguments, but got 4. +!!! error TS2554: Expected 3 arguments, but got 4. !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt b/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt index 4043276dfc5..5288875b0ce 100644 --- a/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt +++ b/tests/baselines/reference/thisExpressionInCallExpressionWithTypeArguments.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts(2,20): error TS2553: Expected 1-2 arguments, but got 1. +tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts(2,20): error TS2554: Expected 1-2 arguments, but got 1. ==== tests/cases/compiler/thisExpressionInCallExpressionWithTypeArguments.ts (1 errors) ==== class C { public foo() { [1,2,3].map((x) => { return this; })} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 1. +!!! error TS2554: Expected 1-2 arguments, but got 1. } \ No newline at end of file diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt index c9e7dfcc490..ad8978847f4 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt @@ -10,26 +10,26 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(62,97): er Object literal may only specify known properties, and 'explicitStructural' does not exist in type '{ y: string; f: (this: { y: number; }, x: number) => number; }'. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(63,110): error TS2322: Type '{ wrongName: number; explicitStructural: (this: { y: number; }, x: number) => number; }' is not assignable to type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. Object literal may only specify known properties, and 'explicitStructural' does not exist in type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(65,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(65,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(66,6): error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(67,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(67,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(68,1): error TS2684: The 'this' context of type '{ y: string; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. Types of property 'y' are incompatible. Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(69,1): error TS2684: The 'this' context of type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. Property 'y' is missing in type '{ wrongName: number; f: (this: { y: number; }, x: number) => number; }'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(72,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(72,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(73,13): error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(74,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(75,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(74,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(75,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(76,16): error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(77,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(78,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(77,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(78,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(79,16): error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(80,1): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(81,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(80,1): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(81,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(82,20): error TS2345: Argument of type '"wrong type 3"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(83,1): error TS2553: Expected 1 arguments, but got 2. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(83,1): error TS2554: Expected 1 arguments, but got 2. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(86,5): error TS2322: Type '(this: { y: number; }, x: number) => number' is not assignable to type '(this: void, x: number) => number'. The 'this' types of each signature are incompatible. Type 'void' is not assignable to type '{ y: number; }'. @@ -187,13 +187,13 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e ok.f(); // not enough arguments ~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. ok.f('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. ok.f(13, 'too many arguments'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. wrongPropertyType.f(13); ~~~~~~~~~~~~~~~~~ !!! error TS2684: The 'this' context of type '{ y: string; f: (this: { y: number; }, x: number) => number; }' is not assignable to method's 'this' of type '{ y: number; }'. @@ -207,40 +207,40 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(175,35): e let c = new C(); c.explicitC(); // not enough arguments ~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. c.explicitC('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. c.explicitC(13, 'too many arguments'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. c.explicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. c.explicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. c.explicitThis(14, 'too many arguments 2'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. c.implicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. c.implicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. c.implicitThis(14, 'too many arguments 2'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. c.explicitProperty(); // not enough arguments ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. c.explicitProperty('wrong type 3'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 3"' is not assignable to parameter of type 'number'. c.explicitProperty(15, 'too many arguments 3'); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. // oops, this triggers contextual typing, which needs to be updated to understand that =>'s `this` is void. let specifiedToVoid: (this: void, x: number) => number = explicitStructural; diff --git a/tests/baselines/reference/tooManyTypeParameters1.errors.txt b/tests/baselines/reference/tooManyTypeParameters1.errors.txt index 9bbb6665bc0..7997e68b575 100644 --- a/tests/baselines/reference/tooManyTypeParameters1.errors.txt +++ b/tests/baselines/reference/tooManyTypeParameters1.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2557: Expected 1 type arguments, but got 2. -tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2557: Expected 1 type arguments, but got 2. -tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2557: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(2,1): error TS2558: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(5,1): error TS2558: Expected 1 type arguments, but got 2. +tests/cases/compiler/tooManyTypeParameters1.ts(8,9): error TS2558: Expected 1 type arguments, but got 2. tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type 'I' requires 1 type argument(s). @@ -8,17 +8,17 @@ tests/cases/compiler/tooManyTypeParameters1.ts(11,8): error TS2314: Generic type function f() { } f(); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 1 type arguments, but got 2. +!!! error TS2558: Expected 1 type arguments, but got 2. var x = () => {}; x(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 1 type arguments, but got 2. +!!! error TS2558: Expected 1 type arguments, but got 2. class C {} var c = new C(); ~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected 1 type arguments, but got 2. +!!! error TS2558: Expected 1 type arguments, but got 2. interface I {} var i: I; diff --git a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt index 5f52dea520a..5c916331950 100644 --- a/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt +++ b/tests/baselines/reference/typeArgumentsOnFunctionsWithNoTypeParameters.errors.txt @@ -1,19 +1,19 @@ -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(2,13): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(3,15): error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. -tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts(4,13): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/typeArgumentsOnFunctionsWithNoTypeParameters.ts (3 errors) ==== function foo(f: (v: T) => U) { var r1 = f(1); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r2 = f(1); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'T'. var r3 = f(null); ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var r4 = f(null); } \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt index be41618433a..0df5d91865d 100644 --- a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt +++ b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(5,13): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/compiler/typeAssertionToGenericFunctionType.ts (2 errors) ==== @@ -12,4 +12,4 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2553: E !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. x.b(); // error ~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index 3787e2e67d4..45f20437860 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(5,5): error TS2558: Expected 0 type arguments, but got 1. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(31,12): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeBase'. Property 'p' is missing in type 'SomeOther'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(35,15): error TS2352: Type 'SomeOther' cannot be converted to type 'SomeDerived'. @@ -30,7 +30,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err fn1(fn2(4)); // Error ~~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var a: any; var s: string; diff --git a/tests/baselines/reference/typesWithPublicConstructor.errors.txt b/tests/baselines/reference/typesWithPublicConstructor.errors.txt index e46fe7e0ddd..d3b03740bf2 100644 --- a/tests/baselines/reference/typesWithPublicConstructor.errors.txt +++ b/tests/baselines/reference/typesWithPublicConstructor.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(8,5): error TS2322: Type 'Function' is not assignable to type '() => void'. Type 'Function' provides no match for the signature '(): void'. -tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/types/members/typesWithPublicConstructor.ts (2 errors) ==== @@ -23,5 +23,5 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): erro var c2 = new C2(); ~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var r2: (x: number) => void = c2.constructor; \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures.errors.txt b/tests/baselines/reference/unionTypeCallSignatures.errors.txt index 7e0b99d92a5..c123dc8da56 100644 --- a/tests/baselines/reference/unionTypeCallSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures.errors.txt @@ -1,34 +1,34 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(9,43): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(10,29): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(15,29): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(16,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(16,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(19,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(20,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(21,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: number) => number) | ((a: string) => Date)' has no compatible call signatures. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(24,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(24,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(26,36): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(29,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(30,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(31,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((a: string) => string) | ((a: string, b: number) => number)' has no compatible call signatures. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(36,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(37,12): error TS2553: Expected 1-2 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(40,12): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(37,12): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(40,12): error TS2554: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(42,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(43,12): error TS2553: Expected 2 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(47,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(48,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(49,12): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(43,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(47,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(48,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(49,12): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(55,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2554: Expected at least 1 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(59,12): error TS2553: Expected 2 arguments, but got 1. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(61,12): error TS2553: Expected 2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(56,12): error TS2555: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(59,12): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(61,12): error TS2554: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeCallSignatures.ts(62,45): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(63,12): error TS2553: Expected 2 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(67,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(68,12): error TS2553: Expected 1 arguments, but got 3. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(69,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(70,12): error TS2553: Expected 1 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(63,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(67,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(68,12): error TS2554: Expected 1 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(69,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(70,12): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2554: Expected 2 arguments, but got 1. ==== tests/cases/conformance/types/union/unionTypeCallSignatures.ts (31 errors) ==== @@ -55,7 +55,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var unionOfDifferentParameterTypes: { (a: number): number; } | { (a: string): Date; }; unionOfDifferentParameterTypes(10);// error - no call signatures @@ -71,7 +71,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 var unionOfDifferentNumberOfSignatures: { (a: number): number; } | { (a: number): Date; (a: string): boolean; }; unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. unionOfDifferentNumberOfSignatures(10); // error - no call signatures unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -96,31 +96,31 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. var unionWithOptionalParameter2: { (a: string, b?: number): string; } | { (a: string, b: number): number }; strOrNum = unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 0. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithOptionalParameter3: { (a: string, b?: number): string; } | { (a: string): number; }; strOrNum = unionWithOptionalParameter3('hello'); strOrNum = unionWithOptionalParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithOptionalParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var unionWithRestParameter1: { (a: string, ...b: number[]): string; } | { (a: string, ...b: number[]): number }; strOrNum = unionWithRestParameter1('hello'); @@ -131,41 +131,41 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected at least 1 arguments, but got 0. +!!! error TS2555: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { (a: string, ...b: number[]): string; } | { (a: string, b: number): number }; strOrNum = unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = unionWithRestParameter2('hello', 10); // error no call signature strOrNum = unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 3. +!!! error TS2554: Expected 2 arguments, but got 3. strOrNum = unionWithRestParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 0. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithRestParameter3: { (a: string, ...b: number[]): string; } | { (a: string): number }; strOrNum = unionWithRestParameter3('hello'); strOrNum = unionWithRestParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithRestParameter3('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 3. +!!! error TS2554: Expected 1 arguments, but got 3. strOrNum = unionWithRestParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var unionWithRestParameter4: { (...a: string[]): string; } | { (a: string, b: string): number; }; strOrNum = unionWithRestParameter4("hello"); // error supplied parameters do not match any call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = unionWithRestParameter4("hello", "world"); \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt index f3c489807a6..1d9c3d272f0 100644 --- a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(10,1): error TS2553: Expected 1-2 arguments, but got 3. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(20,1): error TS2553: Expected 1-2 arguments, but got 3. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(23,1): error TS2553: Expected 2 arguments, but got 1. -tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2553: Expected 2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(10,1): error TS2554: Expected 1-2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(20,1): error TS2554: Expected 1-2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(23,1): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2554: Expected 2 arguments, but got 3. ==== tests/cases/conformance/types/union/unionTypeCallSignatures4.ts (4 errors) ==== @@ -16,7 +16,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f12("a", "b"); f12("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 3. +!!! error TS2554: Expected 1-2 arguments, but got 3. var f34: F3 | F4; f34("a"); @@ -28,14 +28,14 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f1234("a", "b"); f1234("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 3. +!!! error TS2554: Expected 1-2 arguments, but got 3. var f12345: F1 | F2 | F3 | F4 | F5; f12345("a"); // error ~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. f12345("a", "b"); f12345("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 3. +!!! error TS2554: Expected 2 arguments, but got 3. \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt index bcfa70b925a..8b4c6f9aa0c 100644 --- a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt @@ -1,33 +1,33 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(9,47): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(10,33): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(15,33): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(16,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(16,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(19,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(20,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(21,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(24,1): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(24,1): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(26,40): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(29,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(30,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(31,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(36,53): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(37,12): error TS2553: Expected 1-2 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(40,12): error TS2553: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(37,12): error TS2554: Expected 1-2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(40,12): error TS2554: Expected 2 arguments, but got 1. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(42,53): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(43,12): error TS2553: Expected 2 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(47,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(48,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(49,12): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(43,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(47,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(48,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(49,12): error TS2554: Expected 1 arguments, but got 0. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(55,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2554: Expected at least 1 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(59,12): error TS2553: Expected 2 arguments, but got 1. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(61,12): error TS2553: Expected 2 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(56,12): error TS2555: Expected at least 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(59,12): error TS2554: Expected 2 arguments, but got 1. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(61,12): error TS2554: Expected 2 arguments, but got 3. tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(62,49): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(63,12): error TS2553: Expected 2 arguments, but got 0. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(67,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(68,12): error TS2553: Expected 1 arguments, but got 3. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(69,12): error TS2553: Expected 1 arguments, but got 2. -tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): error TS2553: Expected 1 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(63,12): error TS2554: Expected 2 arguments, but got 0. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(67,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(68,12): error TS2554: Expected 1 arguments, but got 3. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(69,12): error TS2554: Expected 1 arguments, but got 2. +tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): error TS2554: Expected 1 arguments, but got 0. ==== tests/cases/conformance/types/union/unionTypeConstructSignatures.ts (30 errors) ==== @@ -54,7 +54,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. new unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var unionOfDifferentParameterTypes: { new (a: number): number; } | { new (a: string): Date; }; new unionOfDifferentParameterTypes(10);// error - no call signatures @@ -70,7 +70,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro var unionOfDifferentNumberOfSignatures: { new (a: number): number; } | { new (a: number): Date; new (a: string): boolean; }; new unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. new unionOfDifferentNumberOfSignatures(10); // error - no call signatures new unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -95,31 +95,31 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1-2 arguments, but got 0. +!!! error TS2554: Expected 1-2 arguments, but got 0. var unionWithOptionalParameter2: { new (a: string, b?: number): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = new unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = new unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 0. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithOptionalParameter3: { new (a: string, b?: number): string; } | { new (a: string): number; }; strOrNum = new unionWithOptionalParameter3('hello'); // error no call signature strOrNum = new unionWithOptionalParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithOptionalParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. +!!! error TS2554: Expected 1 arguments, but got 0. var unionWithRestParameter1: { new (a: string, ...b: number[]): string; } | { new (a: string, ...b: number[]): number }; strOrNum = new unionWithRestParameter1('hello'); @@ -130,34 +130,34 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected at least 1 arguments, but got 0. +!!! error TS2555: Expected at least 1 arguments, but got 0. var unionWithRestParameter2: { new (a: string, ...b: number[]): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 1. +!!! error TS2554: Expected 2 arguments, but got 1. strOrNum = new unionWithRestParameter2('hello', 10); // error no call signature strOrNum = new unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 3. +!!! error TS2554: Expected 2 arguments, but got 3. strOrNum = new unionWithRestParameter2('hello', "hello"); // error no call signature ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. strOrNum = new unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 2 arguments, but got 0. +!!! error TS2554: Expected 2 arguments, but got 0. var unionWithRestParameter3: { new (a: string, ...b: number[]): string; } | { new (a: string): number }; strOrNum = new unionWithRestParameter3('hello'); // error no call signature strOrNum = new unionWithRestParameter3('hello', 10); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 3. +!!! error TS2554: Expected 1 arguments, but got 3. strOrNum = new unionWithRestParameter3('hello', "hello"); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 2. +!!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2553: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file diff --git a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt index ee51408b19f..6b6594fc1ed 100644 --- a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt +++ b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.errors.txt @@ -1,13 +1,13 @@ -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(3,10): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(5,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(8,10): error TS2347: Untyped function calls may not accept type arguments. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(10,7): error TS2420: Class 'C' incorrectly implements interface 'Function'. Property 'apply' is missing in type 'C'. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(18,10): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'C' has no compatible call signatures. tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(22,10): error TS2347: Untyped function calls may not accept type arguments. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2557: Expected 0 type arguments, but got 1. -tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2557: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(28,10): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(35,1): error TS2558: Expected 0 type arguments, but got 1. +tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2558: Expected 0 type arguments, but got 1. ==== tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts (9 errors) ==== @@ -15,7 +15,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var x = function () { return; }; var r1 = x(); ~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. var y: any = x; var r2 = y(); ~~~~~~~~~~~ @@ -53,7 +53,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var z: I; var r6 = z(1); // error ~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. interface callable2 { (a: T): T; @@ -62,7 +62,7 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c4: callable2; c4(1); ~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. interface callable3 { (a: T): T; } @@ -70,6 +70,6 @@ tests/cases/compiler/untypedFunctionCallsWithTypeParameters1.ts(41,1): error TS2 var c5: callable3; c5(1); // error ~~~~~~~~~~~~~ -!!! error TS2557: Expected 0 type arguments, but got 1. +!!! error TS2558: Expected 0 type arguments, but got 1. \ No newline at end of file From b9efe3e700deb7f4558caae0ed41ac143c2b3663 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 18 May 2017 13:57:24 -0700 Subject: [PATCH 236/282] Retain undefined in spreads w/strictNullChecks Previously, both optional and `| undefined` caused spread properties to combine with preceding properties and drop the `undefined`. Now, with strictNullChecks, optional and `| undefined` properties still combine with preceding properties but don't drop the `undefined`. --- src/compiler/checker.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dde8033d1e9..e4ea3740a62 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7640,11 +7640,11 @@ namespace ts { if (members.has(leftProp.name)) { const rightProp = members.get(leftProp.name); const rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, TypeFlags.Undefined) || rightProp.flags & SymbolFlags.Optional) { + if (rightProp.flags & SymbolFlags.Optional) { const declarations: Declaration[] = concatenate(leftProp.declarations, rightProp.declarations); const flags = SymbolFlags.Property | (leftProp.flags & SymbolFlags.Optional); const result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, TypeFacts.NEUndefined)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; From db3696c789071c28d1f6184475ceefcdd66bc422 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 18 May 2017 13:59:07 -0700 Subject: [PATCH 237/282] Test:retain undefined in spreads w/strictNullChecks Add test case and update baselines with new errors --- .../objectSpreadStrictNull.errors.txt | 84 +++++++++++++++++++ .../reference/objectSpreadStrictNull.js | 12 +++ .../types/spread/objectSpreadStrictNull.ts | 9 ++ 3 files changed, 105 insertions(+) create mode 100644 tests/baselines/reference/objectSpreadStrictNull.errors.txt diff --git a/tests/baselines/reference/objectSpreadStrictNull.errors.txt b/tests/baselines/reference/objectSpreadStrictNull.errors.txt new file mode 100644 index 00000000000..f3c5cc7de25 --- /dev/null +++ b/tests/baselines/reference/objectSpreadStrictNull.errors.txt @@ -0,0 +1,84 @@ +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(9,9): error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'string | number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(10,9): error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'string | number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(14,9): error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(15,9): error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. + Types of property 'sn' are incompatible. + Type 'number | undefined' is not assignable to type 'string | number'. + Type 'undefined' is not assignable to type 'string | number'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(18,9): error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number | boolean; }'. + Types of property 'sn' are incompatible. + Type 'string | number | undefined' is not assignable to type 'string | number | boolean'. + Type 'undefined' is not assignable to type 'string | number | boolean'. +tests/cases/conformance/types/spread/objectSpreadStrictNull.ts(28,7): error TS2322: Type '{ title: undefined; yearReleased: number; }' is not assignable to type 'Movie'. + Types of property 'title' are incompatible. + Type 'undefined' is not assignable to type 'string'. + + +==== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts (6 errors) ==== + function f( + definiteBoolean: { sn: boolean }, + definiteString: { sn: string }, + optionalString: { sn?: string }, + optionalNumber: { sn?: number }, + undefinedString: { sn: string | undefined }, + undefinedNumber: { sn: number | undefined }) { + // optional + let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'string | number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; + ~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'string | number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; + + // undefined + let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; + ~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: number | undefined; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'number | undefined' is not assignable to type 'string | number'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number'. + let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; + + let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ sn: string | number | undefined; }' is not assignable to type '{ sn: string | number | boolean; }'. +!!! error TS2322: Types of property 'sn' are incompatible. +!!! error TS2322: Type 'string | number | undefined' is not assignable to type 'string | number | boolean'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | number | boolean'. + } + + type Movie = { + title: string; + yearReleased: number; + } + + const m = { title: "The Matrix", yearReleased: 1999 }; + // should error here because title: undefined is not assignable to string + const x: Movie = { ...m, title: undefined }; + ~ +!!! error TS2322: Type '{ title: undefined; yearReleased: number; }' is not assignable to type 'Movie'. +!!! error TS2322: Types of property 'title' are incompatible. +!!! error TS2322: Type 'undefined' is not assignable to type 'string'. + \ No newline at end of file diff --git a/tests/baselines/reference/objectSpreadStrictNull.js b/tests/baselines/reference/objectSpreadStrictNull.js index 8a4cf0e5f9f..a21b5e2467c 100644 --- a/tests/baselines/reference/objectSpreadStrictNull.js +++ b/tests/baselines/reference/objectSpreadStrictNull.js @@ -18,6 +18,15 @@ function f( let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; } + +type Movie = { + title: string; + yearReleased: number; +} + +const m = { title: "The Matrix", yearReleased: 1999 }; +// should error here because title: undefined is not assignable to string +const x: Movie = { ...m, title: undefined }; //// [objectSpreadStrictNull.js] @@ -40,3 +49,6 @@ function f(definiteBoolean, definiteString, optionalString, optionalNumber, unde var allUndefined = __assign({}, undefinedString, undefinedNumber); var undefinedWithOptionalContinues = __assign({}, definiteBoolean, undefinedString, optionalNumber); } +var m = { title: "The Matrix", yearReleased: 1999 }; +// should error here because title: undefined is not assignable to string +var x = __assign({}, m, { title: undefined }); diff --git a/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts b/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts index 087d47df26c..979a6feed03 100644 --- a/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts +++ b/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts @@ -19,3 +19,12 @@ function f( let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; } + +type Movie = { + title: string; + yearReleased: number; +} + +const m = { title: "The Matrix", yearReleased: 1999 }; +// should error here because title: undefined is not assignable to string +const x: Movie = { ...m, title: undefined }; From 4e03d7b0f6334ebc5809ec0c8f67d22085614c92 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 18 May 2017 14:01:57 -0700 Subject: [PATCH 238/282] Remove stale baselines --- .../reference/objectSpreadStrictNull.symbols | 80 ----------------- .../reference/objectSpreadStrictNull.types | 87 ------------------- 2 files changed, 167 deletions(-) delete mode 100644 tests/baselines/reference/objectSpreadStrictNull.symbols delete mode 100644 tests/baselines/reference/objectSpreadStrictNull.types diff --git a/tests/baselines/reference/objectSpreadStrictNull.symbols b/tests/baselines/reference/objectSpreadStrictNull.symbols deleted file mode 100644 index e9202767945..00000000000 --- a/tests/baselines/reference/objectSpreadStrictNull.symbols +++ /dev/null @@ -1,80 +0,0 @@ -=== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts === -function f( ->f : Symbol(f, Decl(objectSpreadStrictNull.ts, 0, 0)) - - definiteBoolean: { sn: boolean }, ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 1, 22)) - - definiteString: { sn: string }, ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 2, 21)) - - optionalString: { sn?: string }, ->optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 2, 35)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 3, 21)) - - optionalNumber: { sn?: number }, ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 4, 21)) - - undefinedString: { sn: string | undefined }, ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 5, 22)) - - undefinedNumber: { sn: number | undefined }) { ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 6, 22)) - - // optional - let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; ->optionalUnionStops : Symbol(optionalUnionStops, Decl(objectSpreadStrictNull.ts, 8, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 8, 29)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) - - let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; ->optionalUnionDuplicates : Symbol(optionalUnionDuplicates, Decl(objectSpreadStrictNull.ts, 9, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 9, 34)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 2, 35)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) - - let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; ->allOptional : Symbol(allOptional, Decl(objectSpreadStrictNull.ts, 10, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 10, 22)) ->optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 2, 35)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) - - // undefined - let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; ->undefinedUnionStops : Symbol(undefinedUnionStops, Decl(objectSpreadStrictNull.ts, 13, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 13, 30)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) - - let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; ->undefinedUnionDuplicates : Symbol(undefinedUnionDuplicates, Decl(objectSpreadStrictNull.ts, 14, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 14, 35)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 1, 37)) ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) - - let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; ->allUndefined : Symbol(allUndefined, Decl(objectSpreadStrictNull.ts, 15, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 15, 23)) ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 5, 48)) - - let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; ->undefinedWithOptionalContinues : Symbol(undefinedWithOptionalContinues, Decl(objectSpreadStrictNull.ts, 17, 7)) ->sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 17, 41)) ->definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 0, 11)) ->undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 4, 36)) ->optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 3, 36)) -} - diff --git a/tests/baselines/reference/objectSpreadStrictNull.types b/tests/baselines/reference/objectSpreadStrictNull.types deleted file mode 100644 index f70f0a9cad2..00000000000 --- a/tests/baselines/reference/objectSpreadStrictNull.types +++ /dev/null @@ -1,87 +0,0 @@ -=== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts === -function f( ->f : (definiteBoolean: { sn: boolean; }, definiteString: { sn: string; }, optionalString: { sn?: string | undefined; }, optionalNumber: { sn?: number | undefined; }, undefinedString: { sn: string | undefined; }, undefinedNumber: { sn: number | undefined; }) => void - - definiteBoolean: { sn: boolean }, ->definiteBoolean : { sn: boolean; } ->sn : boolean - - definiteString: { sn: string }, ->definiteString : { sn: string; } ->sn : string - - optionalString: { sn?: string }, ->optionalString : { sn?: string | undefined; } ->sn : string | undefined - - optionalNumber: { sn?: number }, ->optionalNumber : { sn?: number | undefined; } ->sn : number | undefined - - undefinedString: { sn: string | undefined }, ->undefinedString : { sn: string | undefined; } ->sn : string | undefined - - undefinedNumber: { sn: number | undefined }) { ->undefinedNumber : { sn: number | undefined; } ->sn : number | undefined - - // optional - let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; ->optionalUnionStops : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...optionalNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->optionalNumber : { sn?: number | undefined; } - - let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; ->optionalUnionDuplicates : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->optionalString : { sn?: string | undefined; } ->optionalNumber : { sn?: number | undefined; } - - let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; ->allOptional : { sn?: string | number | undefined; } ->sn : string | number | undefined ->{ ...optionalString, ...optionalNumber } : { sn?: string | number | undefined; } ->optionalString : { sn?: string | undefined; } ->optionalNumber : { sn?: number | undefined; } - - // undefined - let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; ->undefinedUnionStops : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...undefinedNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->undefinedNumber : { sn: number | undefined; } - - let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; ->undefinedUnionDuplicates : { sn: string | number; } ->sn : string | number ->{ ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber } : { sn: string | number; } ->definiteBoolean : { sn: boolean; } ->definiteString : { sn: string; } ->undefinedString : { sn: string | undefined; } ->undefinedNumber : { sn: number | undefined; } - - let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; ->allUndefined : { sn: string | number | undefined; } ->sn : string | number | undefined ->{ ...undefinedString, ...undefinedNumber } : { sn: string | number | undefined; } ->undefinedString : { sn: string | undefined; } ->undefinedNumber : { sn: number | undefined; } - - let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; ->undefinedWithOptionalContinues : { sn: string | number | boolean; } ->sn : string | number | boolean ->{ ...definiteBoolean, ...undefinedString, ...optionalNumber } : { sn: string | number | boolean; } ->definiteBoolean : { sn: boolean; } ->undefinedString : { sn: string | undefined; } ->optionalNumber : { sn?: number | undefined; } -} - From 385debec5f50ff96d561b9a3a52b041e586924c3 Mon Sep 17 00:00:00 2001 From: Blaine Bublitz Date: Thu, 18 May 2017 14:19:30 -0700 Subject: [PATCH 239/282] Make {create/update}TypeAliasDeclaration API consistent (closes #15918) --- src/compiler/factory.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 63c2028c424..80e3e995e38 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -1502,19 +1502,23 @@ namespace ts { : node; } - export function createTypeAliasDeclaration(name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { + export function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { const node = createSynthesizedNode(SyntaxKind.TypeAliasDeclaration); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); node.type = type; return node; } - export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { - return node.name !== name + export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? updateNode(createTypeAliasDeclaration(name, typeParameters, type), node) + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) : node; } From eec82408d59601d3f4ce4cd8c8aa9098c80065d8 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 19 May 2017 07:43:09 -0700 Subject: [PATCH 240/282] Debug.assert(false) -> Debug.fail() --- src/services/findAllReferences.ts | 2 +- src/services/importTracker.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 92ca47cbed6..5687bbfc02b 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -334,7 +334,7 @@ namespace ts.FindAllReferences.Core { references.push({ type: "node", node: (decl as ts.ModuleDeclaration).name }); break; default: - Debug.assert(false); + Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index e8528b366b9..2866ade873b 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -405,7 +405,7 @@ namespace ts.FindAllReferences { case SyntaxKind.ExternalModuleReference: return (decl as ExternalModuleReference).parent; default: - Debug.assert(false); + Debug.fail(`Unexpected module specifier parent: ${decl.kind}`); } } From 8afe9fcc7247d222765dfa6554ece643b7667361 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 19 May 2017 08:12:55 -0700 Subject: [PATCH 241/282] Separate bind worker for JSDoc nodes, and only enter it if in a JS file --- src/compiler/binder.ts | 64 +++++++++++++++++++++++++----------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 65cd8e7ae8f..5e89cd89b98 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -439,7 +439,8 @@ namespace ts { // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - const isJSDocTypedefInJSDocNamespace = isInJavaScriptFile(node) && node.kind === SyntaxKind.JSDocTypedefTag && + if (node.kind === SyntaxKind.JSDocTypedefTag) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag && (node as JSDocTypedefTag).name && (node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier && ((node as JSDocTypedefTag).name as Identifier).isInJSDocNamespace; @@ -603,9 +604,7 @@ namespace ts { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (node.jsDoc) { - forEach(node.jsDoc, bind); - } + forEach(node.jsDoc, bind); if (checkUnreachable(node)) { bindEachChild(node); return; @@ -2071,10 +2070,7 @@ namespace ts { return bindVariableDeclarationOrBindingElement(node); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - case SyntaxKind.JSDocRecordMember: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); - case SyntaxKind.JSDocPropertyTag: - return bindJSDocProperty(node); + return bindPropertyWorker(node as PropertyDeclaration | PropertySignature); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); @@ -2119,13 +2115,10 @@ namespace ts { return bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: - case SyntaxKind.JSDocFunctionType: return bindFunctionOrConstructorType(node); case SyntaxKind.TypeLiteral: case SyntaxKind.MappedType: - case SyntaxKind.JSDocTypeLiteral: - case SyntaxKind.JSDocRecordType: - return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); + return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode); case SyntaxKind.ObjectLiteralExpression: return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: @@ -2146,11 +2139,6 @@ namespace ts { return bindClassLikeDeclaration(node); case SyntaxKind.InterfaceDeclaration: return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); - case SyntaxKind.JSDocTypedefTag: - if (isInJavaScriptFile(node) && (!(node).fullName || (node).fullName.kind === SyntaxKind.Identifier)) { - return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); - } - break; case SyntaxKind.TypeAliasDeclaration: return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); case SyntaxKind.EnumDeclaration: @@ -2188,9 +2176,41 @@ namespace ts { // falls through case SyntaxKind.ModuleBlock: return updateStrictModeStatementList((node).statements); + + default: + if (isInJavaScriptFile(node)) return bindJSDocWorker(node); } } + function bindJSDocWorker(node: Node) { + switch (node.kind) { + case SyntaxKind.JSDocRecordMember: + return bindPropertyWorker(node as JSDocRecordMember); + case SyntaxKind.JSDocPropertyTag: + return declareSymbolAndAddToSymbolTable(node as JSDocPropertyTag, SymbolFlags.Property, SymbolFlags.PropertyExcludes); + case SyntaxKind.JSDocFunctionType: + return bindFunctionOrConstructorType(node); + case SyntaxKind.JSDocTypeLiteral: + case SyntaxKind.JSDocRecordType: + return bindAnonymousTypeWorker(node as JSDocTypeLiteral | JSDocRecordType); + case SyntaxKind.JSDocTypedefTag: { + const { fullName } = node as JSDocTypedefTag; + if (!fullName || fullName.kind === SyntaxKind.Identifier) { + return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); + } + break; + } + } + } + + function bindPropertyWorker(node: PropertyDeclaration | PropertySignature) { + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); + } + + function bindAnonymousTypeWorker(node: TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral | JSDocRecordType) { + return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); + } + function checkTypePredicate(node: TypePredicateNode) { const { parameterName, type } = node; if (parameterName && parameterName.kind === SyntaxKind.Identifier) { @@ -2556,10 +2576,8 @@ namespace ts { } function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { - if (isAsyncFunction(node)) { - emitFlags |= NodeFlags.HasAsyncFunctions; - } + if (!isDeclarationFile(file) && !isInAmbientContext(node) && isAsyncFunction(node)) { + emitFlags |= NodeFlags.HasAsyncFunctions; } if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) { @@ -2571,10 +2589,6 @@ namespace ts { : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - function bindJSDocProperty(node: JSDocPropertyTag) { - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); - } - // reachability checks function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean { From ce1e0097f08b344adf5aa31aed0e6a752f39a86d Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 19 May 2017 08:56:56 -0700 Subject: [PATCH 242/282] Unconditionally compute type arguments of class base type --- src/compiler/checker.ts | 3 ++- .../parserGenericsInTypeContexts1.errors.txt | 5 ++++- .../parserGenericsInTypeContexts2.errors.txt | 17 ++++++++++++++++- .../unusedInvalidTypeArguments.errors.txt | 8 ++++---- .../reference/unusedInvalidTypeArguments.js | 18 +++++++++--------- .../compiler/unusedInvalidTypeArguments.ts | 4 ++-- 6 files changed, 37 insertions(+), 18 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 799cde7cdb3..28b19171db9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4846,6 +4846,7 @@ namespace ts { return; } const baseTypeNode = getBaseTypeNodeOfClass(type); + const typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); let baseType: Type; const originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && @@ -4853,7 +4854,7 @@ namespace ts { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgumentsFromTypeReferenceNode(baseTypeNode)); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & TypeFlags.Any) { baseType = baseConstructorType; diff --git a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt index e98b618d78c..fb7dbacf656 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,17): error TS2304: Cannot find name 'A'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,19): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,33): error TS2304: Cannot find name 'B'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,35): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(4,9): error TS2315: Type 'C' is not generic. @@ -17,10 +18,12 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(14,18): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts (17 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts (18 errors) ==== class C extends A implements B { ~ !!! error TS2304: Cannot find name 'A'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS2304: Cannot find name 'B'. ~ diff --git a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt index 79acb0fb6fd..4fa6016feb7 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt @@ -1,4 +1,9 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,17): error TS2304: Cannot find name 'A'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,19): error TS2304: Cannot find name 'X'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,21): error TS2304: Cannot find name 'T'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,25): error TS2304: Cannot find name 'Y'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,27): error TS2304: Cannot find name 'Z'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,29): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,45): error TS2304: Cannot find name 'B'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,47): error TS2304: Cannot find name 'X'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,49): error TS2304: Cannot find name 'T'. @@ -49,10 +54,20 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,28): error TS2304: Cannot find name 'T'. -==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts (49 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts (54 errors) ==== class C extends A, Y>> implements B, Y>> { ~ !!! error TS2304: Cannot find name 'A'. + ~ +!!! error TS2304: Cannot find name 'X'. + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'Y'. + ~ +!!! error TS2304: Cannot find name 'Z'. + ~ +!!! error TS2304: Cannot find name 'T'. ~ !!! error TS2304: Cannot find name 'B'. ~ diff --git a/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt b/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt index bd78839ab21..d524c717980 100644 --- a/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt +++ b/tests/baselines/reference/unusedInvalidTypeArguments.errors.txt @@ -5,7 +5,7 @@ /classReference.ts(4,24): error TS2315: Type 'C' is not generic. /interface.ts(1,21): error TS2307: Cannot find module 'unknown'. /new.ts(1,21): error TS2307: Cannot find module 'unkown'. -/super.ts(1,19): error TS2307: Cannot find module 'unknown'. +/super.ts(1,22): error TS2307: Cannot find module 'unknown'. /super.ts(8,17): error TS2304: Cannot find name 'InvalidReference'. /typeReference.ts(6,17): error TS2315: Type 'U' is not generic. @@ -61,13 +61,13 @@ !!! error TS2304: Cannot find name 'InvalidReference'. ==== /super.ts (2 errors) ==== - import { C } from "unknown"; - ~~~~~~~~~ + import { A, B } from "unknown"; + ~~~~~~~~~ !!! error TS2307: Cannot find module 'unknown'. type T = number; - export class D extends C { + export class C extends A { m() { super.m(1); super.m(); // Should get error for type argument diff --git a/tests/baselines/reference/unusedInvalidTypeArguments.js b/tests/baselines/reference/unusedInvalidTypeArguments.js index 955845ea01a..9f32181a0fb 100644 --- a/tests/baselines/reference/unusedInvalidTypeArguments.js +++ b/tests/baselines/reference/unusedInvalidTypeArguments.js @@ -35,11 +35,11 @@ g(); g(); // Should get error for type argument //// [super.ts] -import { C } from "unknown"; +import { A, B } from "unknown"; type T = number; -export class D extends C { +export class C extends A { m() { super.m(1); super.m(); // Should get error for type argument @@ -108,15 +108,15 @@ var __extends = (this && this.__extends) || (function () { })(); exports.__esModule = true; var unknown_1 = require("unknown"); -var D = (function (_super) { - __extends(D, _super); - function D() { +var C = (function (_super) { + __extends(C, _super); + function C() { return _super !== null && _super.apply(this, arguments) || this; } - D.prototype.m = function () { + C.prototype.m = function () { _super.prototype.m.call(this, 1); _super.prototype.m.call(this); // Should get error for type argument }; - return D; -}(unknown_1.C)); -exports.D = D; + return C; +}(unknown_1.A)); +exports.C = C; diff --git a/tests/cases/compiler/unusedInvalidTypeArguments.ts b/tests/cases/compiler/unusedInvalidTypeArguments.ts index d0bcf0519a7..3f4d56f8d30 100644 --- a/tests/cases/compiler/unusedInvalidTypeArguments.ts +++ b/tests/cases/compiler/unusedInvalidTypeArguments.ts @@ -34,11 +34,11 @@ g(); g(); // Should get error for type argument // @Filename: /super.ts -import { C } from "unknown"; +import { A, B } from "unknown"; type T = number; -export class D extends C { +export class C extends A { m() { super.m(1); super.m(); // Should get error for type argument From 4cd20b1335b551abfcc4c2d74c3d40e1c1730c3b Mon Sep 17 00:00:00 2001 From: Noel Varanda Date: Fri, 19 May 2017 17:38:04 +0100 Subject: [PATCH 243/282] Fix #15540: Throw error when importing @types (#15866) * Fix #15540: Throw error when importing @types Fix issue: #15540 - Modify checker; external imports to account for imported modules containing '@types/'. - Add diagnostic message. - Add test case * FIX-15540: Review changes - Replace `substr` with `startsWith` - move diagnostics message to more relevant place - Add `removePrefix` helper function --- src/compiler/checker.ts | 6 ++++++ src/compiler/core.ts | 5 +++++ src/compiler/diagnosticMessages.json | 4 ++++ .../reference/importDeclTypes.errors.txt | 14 ++++++++++++++ tests/baselines/reference/importDeclTypes.js | 15 +++++++++++++++ tests/cases/compiler/importDeclTypes.ts | 9 +++++++++ 6 files changed, 53 insertions(+) create mode 100644 tests/baselines/reference/importDeclTypes.errors.txt create mode 100644 tests/baselines/reference/importDeclTypes.js create mode 100644 tests/cases/compiler/importDeclTypes.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 799cde7cdb3..9ce987c3f58 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1642,6 +1642,12 @@ namespace ts { return; } + if (startsWith(moduleReference, "@types/")) { + const diag = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } + const ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 60553fdab01..4cb55f0fe30 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1764,6 +1764,11 @@ namespace ts { return str.lastIndexOf(prefix, 0) === 0; } + /* @internal */ + export function removePrefix(str: string, prefix: string): string { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + /* @internal */ export function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ffedb45c2e0..d4fc40399ed 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3061,6 +3061,10 @@ "category": "Message", "code": 6136 }, + "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'.": { + "category": "Error", + "code": 6137 + }, "Property '{0}' is declared but never used.": { "category": "Error", "code": 6138 diff --git a/tests/baselines/reference/importDeclTypes.errors.txt b/tests/baselines/reference/importDeclTypes.errors.txt new file mode 100644 index 00000000000..dfb8fcb6f48 --- /dev/null +++ b/tests/baselines/reference/importDeclTypes.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/a.ts(1,21): error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'. + + +==== /node_modules/@types/foo-bar/index.d.ts (0 errors) ==== + export interface Foo { + bar: string; + } + + // This should error +==== tests/cases/compiler/a.ts (1 errors) ==== + import { Foo } from "@types/foo-bar"; + ~~~~~~~~~~~~~~~~ +!!! error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'. + \ No newline at end of file diff --git a/tests/baselines/reference/importDeclTypes.js b/tests/baselines/reference/importDeclTypes.js new file mode 100644 index 00000000000..640dd4a19b4 --- /dev/null +++ b/tests/baselines/reference/importDeclTypes.js @@ -0,0 +1,15 @@ +//// [tests/cases/compiler/importDeclTypes.ts] //// + +//// [index.d.ts] +export interface Foo { + bar: string; +} + +// This should error +//// [a.ts] +import { Foo } from "@types/foo-bar"; + + +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/cases/compiler/importDeclTypes.ts b/tests/cases/compiler/importDeclTypes.ts new file mode 100644 index 00000000000..01fcd0e7b6f --- /dev/null +++ b/tests/cases/compiler/importDeclTypes.ts @@ -0,0 +1,9 @@ + +// @filename: /node_modules/@types/foo-bar/index.d.ts +export interface Foo { + bar: string; +} + +// This should error +// @filename: a.ts +import { Foo } from "@types/foo-bar"; From f6fbe617188ac28648aef55a20e18345e6a8986f Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Fri, 19 May 2017 10:18:42 -0700 Subject: [PATCH 244/282] Refactoring support (squash) --- src/compiler/diagnosticMessages.json | 9 + src/compiler/emitter.ts | 28 ++- src/compiler/factory.ts | 4 +- src/compiler/types.ts | 4 +- src/compiler/visitor.ts | 3 +- src/harness/fourslash.ts | 69 +++++- src/harness/harness.ts | 2 +- src/harness/harnessLanguageService.ts | 9 + .../unittests/tsserverProjectSystem.ts | 13 +- src/server/client.ts | 40 ++++ src/server/protocol.ts | 62 +++++- src/server/session.ts | 116 ++++++++-- src/services/codeFixProvider.ts | 6 +- src/services/refactorProvider.ts | 69 ++++++ .../refactors/convertFunctionToEs6Class.ts | 209 ++++++++++++++++++ src/services/refactors/refactors.ts | 1 + src/services/services.ts | 34 +++ src/services/textChanges.ts | 22 +- src/services/tsconfig.json | 37 +--- src/services/types.ts | 7 + .../fourslash/convertFunctionToEs6Class1.ts | 26 +++ .../fourslash/convertFunctionToEs6Class2.ts | 27 +++ .../fourslash/convertFunctionToEs6Class3.ts | 28 +++ tests/cases/fourslash/fourslash.ts | 4 + .../convertFunctionToEs6Class-server.ts | 25 +++ 25 files changed, 776 insertions(+), 78 deletions(-) create mode 100644 src/services/refactorProvider.ts create mode 100644 src/services/refactors/convertFunctionToEs6Class.ts create mode 100644 src/services/refactors/refactors.ts create mode 100644 tests/cases/fourslash/convertFunctionToEs6Class1.ts create mode 100644 tests/cases/fourslash/convertFunctionToEs6Class2.ts create mode 100644 tests/cases/fourslash/convertFunctionToEs6Class3.ts create mode 100644 tests/cases/fourslash/server/convertFunctionToEs6Class-server.ts diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index d4fc40399ed..873c09448fc 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3584,6 +3584,15 @@ "code": 90022 }, + "Convert function to an ES2015 class": { + "category": "Message", + "code": 95001 + }, + "Convert function '{0}' to class": { + "category": "Message", + "code": 95002 + }, + "Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": { "category": "Error", "code": 8017 diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index e5ff7de8353..0348469dae1 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -200,7 +200,9 @@ namespace ts { onSetSourceFile, substituteNode, onBeforeEmitNodeArray, - onAfterEmitNodeArray + onAfterEmitNodeArray, + onBeforeEmitToken, + onAfterEmitToken } = handlers; const newLine = getNewLineCharacter(printerOptions); @@ -406,7 +408,7 @@ namespace ts { // Strict mode reserved words // Contextual keywords if (isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } @@ -645,7 +647,7 @@ namespace ts { } if (isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -672,7 +674,7 @@ namespace ts { case SyntaxKind.SuperKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.ThisKeyword: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions @@ -1260,7 +1262,7 @@ namespace ts { const operand = node.operand; return operand.kind === SyntaxKind.PrefixUnaryExpression && ((node.operator === SyntaxKind.PlusToken && ((operand).operator === SyntaxKind.PlusToken || (operand).operator === SyntaxKind.PlusPlusToken)) - || (node.operator === SyntaxKind.MinusToken && ((operand).operator === SyntaxKind.MinusToken || (operand).operator === SyntaxKind.MinusMinusToken))); + || (node.operator === SyntaxKind.MinusToken && ((operand).operator === SyntaxKind.MinusToken || (operand).operator === SyntaxKind.MinusMinusToken))); } function emitPostfixUnaryExpression(node: PostfixUnaryExpression) { @@ -1275,7 +1277,7 @@ namespace ts { emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -2455,6 +2457,16 @@ namespace ts { : writeTokenText(token, pos); } + function writeTokenNode(node: Node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token: SyntaxKind, pos?: number) { const tokenString = tokenToString(token); write(tokenString); @@ -2928,9 +2940,9 @@ namespace ts { // Flags enum to track count of temp variables and a few dedicated names const enum TempFlags { - Auto = 0x00000000, // No preferred name + Auto = 0x00000000, // No preferred name CountMask = 0x0FFFFFFF, // Temp variable counter - _i = 0x10000000, // Use/preference flag for '_i' + _i = 0x10000000, // Use/preference flag for '_i' } const enum ListFormat { diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 63c2028c424..b0af0c26073 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -984,10 +984,10 @@ namespace ts { return node; } - export function updateBinary(node: BinaryExpression, left: Expression, right: Expression) { + export function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index d5584cc445b..4b95c957f74 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3415,7 +3415,7 @@ namespace ts { export enum DiagnosticCategory { Warning, Error, - Message, + Message } export enum ModuleResolutionKind { @@ -4273,6 +4273,8 @@ namespace ts { /*@internal*/ onSetSourceFile?: (node: SourceFile) => void; /*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray) => void; /*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray) => void; + /*@internal*/ onBeforeEmitToken?: (node: Node) => void; + /*@internal*/ onAfterEmitToken?: (node: Node) => void; } export interface PrinterOptions { diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index eb28721a142..628b14794ea 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -516,7 +516,8 @@ namespace ts { case SyntaxKind.BinaryExpression: return updateBinary(node, visitNode((node).left, visitor, isExpression), - visitNode((node).right, visitor, isExpression)); + visitNode((node).right, visitor, isExpression), + visitNode((node).operatorToken, visitor, isToken)); case SyntaxKind.ConditionalExpression: return updateConditional(node, diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 0ce18e4f8f5..fc50e71478e 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2354,7 +2354,8 @@ namespace FourSlash { private applyCodeAction(fileName: string, actions: ts.CodeAction[], index?: number): void { if (index === undefined) { if (!(actions && actions.length === 1)) { - this.raiseError(`Should find exactly one codefix, but ${actions ? actions.length : "none"} found.`); + const actionText = (actions && actions.length) ? JSON.stringify(actions) : "none"; + this.raiseError(`Should find exactly one codefix, but found ${actionText}`); } index = 0; } @@ -2708,6 +2709,60 @@ namespace FourSlash { } } + public verifyApplicableRefactorAvailableAtMarker(negative: boolean, markerName: string) { + const marker = this.getMarkerByName(markerName); + const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, marker.position); + const isAvailable = applicableRefactors && applicableRefactors.length > 0; + if (negative && isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableAtMarker failed - expected no refactor at marker ${markerName} but found some.`); + } + if (!negative && !isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableAtMarker failed - expected a refactor at marker ${markerName} but found none.`); + } + } + + public verifyApplicableRefactorAvailableForRange(negative: boolean) { + const ranges = this.getRanges(); + if (!(ranges && ranges.length === 1)) { + throw new Error("Exactly one refactor range is allowed per test."); + } + + const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, { pos: ranges[0].start, end: ranges[0].end }); + const isAvailable = applicableRefactors && applicableRefactors.length > 0; + if (negative && isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableForRange failed - expected no refactor but found some.`); + } + if (!negative && !isAvailable) { + this.raiseError(`verifyApplicableRefactorAvailableForRange failed - expected a refactor but found none.`); + } + } + + public verifyFileAfterApplyingRefactorAtMarker( + markerName: string, + expectedContent: string, + refactorNameToApply: string, + formattingOptions?: ts.FormatCodeSettings) { + + formattingOptions = formattingOptions || this.formatCodeSettings; + const markerPos = this.getMarkerByName(markerName).position; + + const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, markerPos); + const applicableRefactorToApply = ts.find(applicableRefactors, refactor => refactor.name === refactorNameToApply); + + if (!applicableRefactorToApply) { + this.raiseError(`The expected refactor: ${refactorNameToApply} is not available at the marker location.`); + } + + const codeActions = this.languageService.getRefactorCodeActions(this.activeFile.fileName, formattingOptions, markerPos, refactorNameToApply); + + this.applyCodeAction(this.activeFile.fileName, codeActions); + const actualContent = this.getFileContent(this.activeFile.fileName); + + if (this.normalizeNewlines(actualContent) !== this.normalizeNewlines(expectedContent)) { + this.raiseError(`verifyFileAfterApplyingRefactors failed: expected:\n${expectedContent}\nactual:\n${actualContent}`); + } + } + public printAvailableCodeFixes() { const codeFixes = this.getCodeFixActions(this.activeFile.fileName); Harness.IO.log(stringify(codeFixes)); @@ -3521,6 +3576,14 @@ namespace FourSlashInterface { public codeFixAvailable() { this.state.verifyCodeFixAvailable(this.negative); } + + public applicableRefactorAvailableAtMarker(markerName: string) { + this.state.verifyApplicableRefactorAvailableAtMarker(this.negative, markerName); + } + + public applicableRefactorAvailableForRange() { + this.state.verifyApplicableRefactorAvailableForRange(this.negative); + } } export class Verify extends VerifyNegatable { @@ -3735,6 +3798,10 @@ namespace FourSlashInterface { this.state.verifyRangeAfterCodeFix(expectedText, includeWhiteSpace, errorCode, index); } + public fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, formattingOptions?: ts.FormatCodeSettings): void { + this.state.verifyFileAfterApplyingRefactorAtMarker(markerName, expectedContent, refactorNameToApply, formattingOptions); + } + public importFixAtPosition(expectedTextArray: string[], errorCode?: number): void { this.state.verifyImportFixAtPosition(expectedTextArray, errorCode); } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index c0ef2672b27..00a04d609f8 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1983,5 +1983,5 @@ namespace Harness { return { unitName: libFile, content: io.readFile(libFile) }; } - if (Error) (Error).stackTraceLimit = 1; + if (Error) (Error).stackTraceLimit = 100; } diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 3bf6f1cde9a..7aefb0f3a1f 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -489,6 +489,15 @@ namespace Harness.LanguageService { getCodeFixesAtPosition(): ts.CodeAction[] { throw new Error("Not supported on the shim."); } + getCodeFixDiagnostics(): ts.Diagnostic[] { + throw new Error("Not supported on the shim."); + } + getRefactorCodeActions(): ts.CodeAction[] { + throw new Error("Not supported on the shim."); + } + getApplicableRefactors(): ts.ApplicableRefactorInfo[] { + throw new Error("Not supported on the shim."); + } getEmitOutput(fileName: string): ts.EmitOutput { return unwrapJSONCallResult(this.shim.getEmitOutput(fileName)); } diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 33838b5805f..efa92490300 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -337,6 +337,7 @@ namespace ts.projectSystem { this.map[timeoutId] = cb.bind(/*this*/ undefined, ...args); return timeoutId; } + unregister(id: any) { if (typeof id === "number") { delete this.map[id]; @@ -352,10 +353,13 @@ namespace ts.projectSystem { } invoke() { + // Note: invoking a callback may result in new callbacks been queued, + // so do not clear the entire callback list regardless. Only remove the + // ones we have invoked. for (const key in this.map) { this.map[key](); + delete this.map[key]; } - this.map = []; } } @@ -3743,7 +3747,7 @@ namespace ts.projectSystem { // run first step host.runQueuedTimeoutCallbacks(); - assert.equal(host.getOutput().length, 1, "expect 1 messages"); + assert.equal(host.getOutput().length, 1, "expect 1 message"); const e1 = getMessage(0); assert.equal(e1.event, "syntaxDiag"); host.clearOutput(); @@ -3765,11 +3769,12 @@ namespace ts.projectSystem { // run first step host.runQueuedTimeoutCallbacks(); - assert.equal(host.getOutput().length, 1, "expect 1 messages"); + assert.equal(host.getOutput().length, 1, "expect 1 message"); const e1 = getMessage(0); assert.equal(e1.event, "syntaxDiag"); host.clearOutput(); + // the semanticDiag message host.runQueuedImmediateCallbacks(); assert.equal(host.getOutput().length, 2, "expect 2 messages"); const e2 = getMessage(0); @@ -3787,7 +3792,7 @@ namespace ts.projectSystem { assert.equal(host.getOutput().length, 0, "expect 0 messages"); // run first step host.runQueuedTimeoutCallbacks(); - assert.equal(host.getOutput().length, 1, "expect 1 messages"); + assert.equal(host.getOutput().length, 1, "expect 1 message"); const e1 = getMessage(0); assert.equal(e1.event, "syntaxDiag"); host.clearOutput(); diff --git a/src/server/client.ts b/src/server/client.ts index 623b00f1ed3..e29261f7244 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -695,6 +695,46 @@ namespace ts.server { return response.body.map(entry => this.convertCodeActions(entry, fileName)); } + private createFileLocationOrRangeRequestArgs(positionOrRange: number | TextRange, fileName: string): protocol.FileLocationOrRangeRequestArgs { + if (typeof positionOrRange === "number") { + const { line, offset } = this.positionToOneBasedLineOffset(fileName, positionOrRange); + return { file: fileName, line, offset }; + } + const { line: startLine, offset: startOffset } = this.positionToOneBasedLineOffset(fileName, positionOrRange.pos); + const { line: endLine, offset: endOffset } = this.positionToOneBasedLineOffset(fileName, positionOrRange.end); + return { + file: fileName, + startLine, + startOffset, + endLine, + endOffset + }; + } + + getApplicableRefactors(fileName: string, positionOrRange: number | TextRange): ApplicableRefactorInfo[] { + const args = this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName); + + const request = this.processRequest(CommandNames.GetApplicableRefactors, args); + const response = this.processResponse(request); + return response.body; + } + + getRefactorCodeActions( + fileName: string, + _formatOptions: FormatCodeSettings, + positionOrRange: number | TextRange, + refactorName: string) { + + const args = this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName) as protocol.GetRefactorCodeActionsRequestArgs; + args.refactorName = refactorName; + + const request = this.processRequest(CommandNames.GetRefactorCodeActions, args); + const response = this.processResponse(request); + const codeActions = response.body.actions; + + return map(codeActions, codeAction => this.convertCodeActions(codeAction, fileName)); + } + convertCodeActions(entry: protocol.CodeAction, fileName: string): CodeAction { return { description: entry.description, diff --git a/src/server/protocol.ts b/src/server/protocol.ts index c4c9ecece2b..8d85ad125d5 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -95,6 +95,10 @@ namespace ts.server.protocol { /* @internal */ export type GetCodeFixesFull = "getCodeFixes-full"; export type GetSupportedCodeFixes = "getSupportedCodeFixes"; + + export type GetApplicableRefactors = "getApplicableRefactors"; + export type GetRefactorCodeActions = "getRefactorCodeActions"; + export type GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; } /** @@ -394,6 +398,54 @@ namespace ts.server.protocol { position?: number; } + export type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + + export interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + + export type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + + export interface ApplicableRefactorInfo { + name: string; + description: string; + } + + export interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + + export interface GetRefactorCodeActionsRequest extends Request { + command: CommandTypes.GetRefactorCodeActions; + arguments: GetRefactorCodeActionsRequestArgs; + } + + export type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & { + /* The kind of the applicable refactor */ + refactorName: string; + }; + + export type RefactorCodeActions = { + actions: protocol.CodeAction[]; + renameLocation?: number + }; + + /* @internal */ + export type RefactorCodeActionsFull = { + actions: ts.CodeAction[]; + renameLocation?: number + }; + + export interface GetRefactorCodeActionsResponse extends Response { + body: RefactorCodeActions; + } + + /* @internal */ + export interface GetRefactorCodeActionsFullResponse extends Response { + body: RefactorCodeActionsFull; + } + /** * Request for the available codefixes at a specific position. */ @@ -402,10 +454,7 @@ namespace ts.server.protocol { arguments: CodeFixRequestArgs; } - /** - * Instances of this interface specify errorcodes on a specific location in a sourcefile. - */ - export interface CodeFixRequestArgs extends FileRequestArgs { + export interface FileRangeRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). */ @@ -437,7 +486,12 @@ namespace ts.server.protocol { */ /* @internal */ endPosition?: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + export interface CodeFixRequestArgs extends FileRangeRequestArgs { /** * Errorcodes we want to get the fixes for. */ diff --git a/src/server/session.ts b/src/server/session.ts index 7be33f8bd2a..bae53dcafe8 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -100,7 +100,7 @@ namespace ts.server { } export interface EventSender { - event(payload: any, eventName: string): void; + event(payload: T, eventName: string): void; } function allEditsBeforePos(edits: ts.TextChange[], pos: number) { @@ -205,6 +205,10 @@ namespace ts.server { /* @internal */ export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full"; export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes"; + + export const GetApplicableRefactors: protocol.CommandTypes.GetApplicableRefactors = "getApplicableRefactors"; + export const GetRefactorCodeActions: protocol.CommandTypes.GetRefactorCodeActions = "getRefactorCodeActions"; + export const GetRefactorCodeActionsFull: protocol.CommandTypes.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; } export function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string { @@ -432,7 +436,7 @@ namespace ts.server { break; case ProjectLanguageServiceStateEvent: const eventName: protocol.ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; - this.event({ + this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled }, eventName); @@ -476,7 +480,7 @@ namespace ts.server { this.send(ev); } - public event(info: any, eventName: string) { + public event(info: T, eventName: string) { const ev: protocol.Event = { seq: 0, type: "event", @@ -511,7 +515,7 @@ namespace ts.server { } const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -523,7 +527,7 @@ namespace ts.server { const diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); - this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); + this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); } } catch (err) { @@ -1366,8 +1370,8 @@ namespace ts.server { return !items ? undefined : simplifiedResult - ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) - : items; + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; } private decorateNavigationTree(tree: ts.NavigationTree, scriptInfo: ScriptInfo): protocol.NavigationTree { @@ -1393,8 +1397,8 @@ namespace ts.server { return !tree ? undefined : simplifiedResult - ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) - : tree; + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; } private getNavigateToItems(args: protocol.NavtoRequestArgs, simplifiedResult: boolean): protocol.NavtoItem[] | NavigateToItem[] { @@ -1481,6 +1485,60 @@ namespace ts.server { return ts.getSupportedCodeFixes(); } + private isLocation(locationOrSpan: protocol.FileLocationOrRangeRequestArgs): locationOrSpan is protocol.FileLocationRequestArgs { + return (locationOrSpan).line !== undefined; + } + + private extractPositionAndRange(args: protocol.FileLocationOrRangeRequestArgs, scriptInfo: ScriptInfo): { position: number, textRange: TextRange } { + let position: number = undefined; + let textRange: TextRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); + textRange = { pos: startPosition, end: endPosition }; + } + return { position, textRange }; + + function getPosition(loc: protocol.FileLocationRequestArgs) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + } + + private getApplicableRefactors(args: protocol.GetApplicableRefactorsRequestArgs): protocol.ApplicableRefactorInfo[] { + const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const { position, textRange } = this.extractPositionAndRange(args, scriptInfo); + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + } + + private getRefactorCodeActions(args: protocol.GetRefactorCodeActionsRequestArgs, simplifiedResult: boolean): protocol.RefactorCodeActions | protocol.RefactorCodeActionsFull { + const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const { position, textRange } = this.extractPositionAndRange(args, scriptInfo); + + const result: ts.CodeAction[] = project.getLanguageService().getRefactorCodeActions( + file, + this.projectService.getFormatCodeOptions(), + position || textRange, + args.refactorName + ); + + if (simplifiedResult) { + // Not full + return { + actions: result.map(action => this.mapCodeAction(action, scriptInfo)) + }; + } + else { + // Full + return { + actions: result + }; + } + } + private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): protocol.CodeAction[] | CodeAction[] { if (args.errorCodes.length === 0) { return undefined; @@ -1488,8 +1546,7 @@ namespace ts.server { const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const startPosition = getStartPosition(); - const endPosition = getEndPosition(); + const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); const formatOptions = this.projectService.getFormatCodeOptions(file); const codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); @@ -1502,14 +1559,28 @@ namespace ts.server { else { return codeActions; } + } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + private getStartAndEndPosition(args: protocol.FileRangeRequestArgs, scriptInfo: ScriptInfo) { + let startPosition: number = undefined, endPosition: number = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; + } + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + // save the result so we don't always recompute + args.startPosition = startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + if (args.endPosition !== undefined) { + endPosition = args.endPosition; } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + + return { startPosition, endPosition }; } private mapCodeAction(codeAction: CodeAction, scriptInfo: ScriptInfo): protocol.CodeAction { @@ -1540,8 +1611,8 @@ namespace ts.server { return !spans ? undefined : simplifiedResult - ? spans.map(span => this.decorateSpan(span, scriptInfo)) - : spans; + ? spans.map(span => this.decorateSpan(span, scriptInfo)) + : spans; } private getDiagnosticsForProject(next: NextStep, delay: number, fileName: string): void { @@ -1846,6 +1917,15 @@ namespace ts.server { }, [CommandNames.GetSupportedCodeFixes]: () => { return this.requiredResponse(this.getSupportedCodeFixes()); + }, + [CommandNames.GetApplicableRefactors]: (request: protocol.GetApplicableRefactorsRequest) => { + return this.requiredResponse(this.getApplicableRefactors(request.arguments)); + }, + [CommandNames.GetRefactorCodeActions]: (request: protocol.GetRefactorCodeActionsRequest) => { + return this.requiredResponse(this.getRefactorCodeActions(request.arguments, /*simplifiedResult*/ true)); + }, + [CommandNames.GetRefactorCodeActionsFull]: (request: protocol.GetRefactorCodeActionsRequest) => { + return this.requiredResponse(this.getRefactorCodeActions(request.arguments, /*simplifiedResult*/ false)); } }); @@ -1903,7 +1983,7 @@ namespace ts.server { let request: protocol.Request; try { request = JSON.parse(message); - const {response, responseRequired} = this.executeCommand(request); + const { response, responseRequired } = this.executeCommand(request); if (this.logger.hasLevel(LogLevel.requestTime)) { const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index bab5356e99c..6ff78572f82 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -19,14 +19,14 @@ namespace ts { export namespace codefix { const codeFixes: CodeFix[][] = []; - export function registerCodeFix(action: CodeFix) { - forEach(action.errorCodes, error => { + export function registerCodeFix(codeFix: CodeFix) { + forEach(codeFix.errorCodes, error => { let fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts new file mode 100644 index 00000000000..0b6ea3487ec --- /dev/null +++ b/src/services/refactorProvider.ts @@ -0,0 +1,69 @@ +/* @internal */ +namespace ts { + export interface Refactor { + /** An unique code associated with each refactor */ + name: string; + + /** Description of the refactor to display in the UI of the editor */ + description: string; + + /** Compute the associated code actions */ + getCodeActions(context: RefactorContext): CodeAction[]; + + /** A fast syntactic check to see if the refactor is applicable at given position. */ + isApplicable(context: RefactorContext): boolean; + } + + export interface RefactorContext { + file: SourceFile; + startPosition: number; + endPosition?: number; + program: Program; + newLineCharacter: string; + rulesProvider?: formatting.RulesProvider; + cancellationToken?: CancellationToken; + } + + export namespace refactor { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + const refactors: Map = createMap(); + + export function registerRefactor(refactor: Refactor) { + refactors.set(refactor.name, refactor); + } + + export function getApplicableRefactors(context: RefactorContext): ApplicableRefactorInfo[] | undefined { + + let results: ApplicableRefactorInfo[]; + const refactorList: Refactor[] = []; + refactors.forEach(refactor => { + refactorList.push(refactor); + }); + for (const refactor of refactorList) { + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor.isApplicable(context)) { + (results || (results = [])).push({ name: refactor.name, description: refactor.description }); + } + } + return results; + } + + export function getRefactorCodeActions(context: RefactorContext, refactorName: string): CodeAction[] | undefined { + + let result: CodeAction[]; + const refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + + const codeActions = refactor.getCodeActions(context); + if (codeActions) { + addRange((result || (result = [])), codeActions); + } + return result; + } + } +} diff --git a/src/services/refactors/convertFunctionToEs6Class.ts b/src/services/refactors/convertFunctionToEs6Class.ts new file mode 100644 index 00000000000..3f1a359c7a1 --- /dev/null +++ b/src/services/refactors/convertFunctionToEs6Class.ts @@ -0,0 +1,209 @@ +/* @internal */ + +namespace ts.refactor { + const convertFunctionToES6Class: Refactor = { + name: "Convert to ES2015 class", + description: Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions, + isApplicable + }; + + registerRefactor(convertFunctionToES6Class); + + function isApplicable(context: RefactorContext): boolean { + const start = context.startPosition; + const node = getTokenAtPosition(context.file, start); + const checker = context.program.getTypeChecker(); + let symbol = checker.getSymbolAtLocation(node); + + if (symbol && isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = (symbol.valueDeclaration as VariableDeclaration).initializer.symbol; + } + + return symbol && symbol.flags & SymbolFlags.Function && symbol.members && symbol.members.size > 0; + } + + function getCodeActions(context: RefactorContext): CodeAction[] | undefined { + const start = context.startPosition; + const sourceFile = context.file; + const checker = context.program.getTypeChecker(); + const token = getTokenAtPosition(sourceFile, start); + const ctorSymbol = checker.getSymbolAtLocation(token); + const newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + + const deletedNodes: Node[] = []; + const deletes: (() => any)[] = []; + + if (!(ctorSymbol.flags & (SymbolFlags.Function | SymbolFlags.Variable))) { + return []; + } + + const ctorDeclaration = ctorSymbol.valueDeclaration; + const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context as { newLineCharacter: string, rulesProvider: formatting.RulesProvider }); + + let precedingNode: Node; + let newClassDeclaration: ClassDeclaration; + switch (ctorDeclaration.kind) { + case SyntaxKind.FunctionDeclaration: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration as FunctionDeclaration); + break; + + case SyntaxKind.VariableDeclaration: + precedingNode = ctorDeclaration.parent.parent; + if ((ctorDeclaration.parent).declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration as VariableDeclaration); + break; + } + + if (!newClassDeclaration) { + return []; + } + + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (const deleteCallback of deletes) { + deleteCallback(); + } + + return [{ + description: formatStringFromArgs(Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + + function deleteNode(node: Node, inList = false) { + if (deletedNodes.some(n => isNodeDescendantOf(node, n))) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(() => changeTracker.deleteNodeInList(sourceFile, node)); + } + else { + deletes.push(() => changeTracker.deleteNode(sourceFile, node)); + } + } + + function createClassElementsFromSymbol(symbol: Symbol) { + const memberElements: ClassElement[] = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(member => { + const memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(member => { + const memberElement = createClassElement(member, [createToken(SyntaxKind.StaticKeyword)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + + return memberElements; + + function shouldConvertDeclaration(_target: PropertyAccessExpression, source: Expression) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return isFunctionLike(source); + } + + function createClassElement(symbol: Symbol, modifiers: Modifier[]): ClassElement { + // both properties and methods are bound as property symbols + if (!(symbol.flags & SymbolFlags.Property)) { + return; + } + + const memberDeclaration = symbol.valueDeclaration as PropertyAccessExpression; + const assignmentBinaryExpression = memberDeclaration.parent as BinaryExpression; + + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === SyntaxKind.ExpressionStatement + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + + if (!assignmentBinaryExpression.right) { + return createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + + switch (assignmentBinaryExpression.right.kind) { + case SyntaxKind.FunctionExpression: + const functionExpression = assignmentBinaryExpression.right as FunctionExpression; + return createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + + case SyntaxKind.ArrowFunction: + const arrowFunction = assignmentBinaryExpression.right as ArrowFunction; + const arrowFunctionBody = arrowFunction.body; + let bodyBlock: Block; + + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === SyntaxKind.Block) { + bodyBlock = arrowFunctionBody as Block; + } + // case 2: () => [1,2,3] + else { + const expression = arrowFunctionBody as Expression; + bodyBlock = createBlock([createReturn(expression)]); + } + return createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + + default: + // Don't try to declare members in JavaScript files + if (isSourceFileJavaScript(sourceFile)) { + return; + } + return createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + + function createClassFromVariableDeclaration(node: VariableDeclaration): ClassDeclaration { + const initializer = node.initializer as FunctionExpression; + if (!initializer || initializer.kind !== SyntaxKind.FunctionExpression) { + return undefined; + } + + if (node.name.kind !== SyntaxKind.Identifier) { + return undefined; + } + + const memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + + return createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + + function createClassFromFunctionDeclaration(node: FunctionDeclaration): ClassDeclaration { + const memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } +} \ No newline at end of file diff --git a/src/services/refactors/refactors.ts b/src/services/refactors/refactors.ts new file mode 100644 index 00000000000..4c4ecb33416 --- /dev/null +++ b/src/services/refactors/refactors.ts @@ -0,0 +1 @@ +/// diff --git a/src/services/services.ts b/src/services/services.ts index 723df40f3f0..1a1ac47847f 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -25,7 +25,9 @@ /// /// /// +/// /// +/// namespace ts { /** The version of the language service API */ @@ -1959,11 +1961,43 @@ namespace ts { return Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file: SourceFile, positionOrRange: number | TextRange, formatOptions?: FormatCodeSettings): RefactorContext { + const [startPosition, endPosition] = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end]; + return { + file, + startPosition, + endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken + }; + } + + function getApplicableRefactors(fileName: string, positionOrRange: number | TextRange): ApplicableRefactorInfo[] { + synchronizeHostData(); + const file = getValidSourceFile(fileName); + return refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + + function getRefactorCodeActions( + fileName: string, + formatOptions: FormatCodeSettings, + positionOrRange: number | TextRange, + refactorName: string): CodeAction[] | undefined { + + synchronizeHostData(); + const file = getValidSourceFile(fileName); + return refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } + return { dispose, cleanupSemanticCache, getSyntacticDiagnostics, getSemanticDiagnostics, + getApplicableRefactors, + getRefactorCodeActions, getCompilerOptionsDiagnostics, getSyntacticClassifications, getSemanticClassifications, diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 5a1aaa21bcd..0551917b33c 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -157,7 +157,7 @@ namespace ts.textChanges { private changes: Change[] = []; private readonly newLineCharacter: string; - public static fromCodeFixContext(context: CodeFixContext) { + public static fromCodeFixContext(context: { newLineCharacter: string, rulesProvider: formatting.RulesProvider }) { return new ChangeTracker(context.newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed, context.rulesProvider); } @@ -254,9 +254,9 @@ namespace ts.textChanges { public insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node, options: InsertNodeOptions & ConfigurableEnd = {}) { if ((isStatementButNotDeclaration(after)) || - after.kind === SyntaxKind.PropertyDeclaration || - after.kind === SyntaxKind.PropertySignature || - after.kind === SyntaxKind.MethodSignature) { + after.kind === SyntaxKind.PropertyDeclaration || + after.kind === SyntaxKind.PropertySignature || + after.kind === SyntaxKind.MethodSignature) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== CharacterCodes.semicolon) { @@ -481,7 +481,7 @@ namespace ts.textChanges { return (options.prefix || "") + text + (options.suffix || ""); } - private static normalize(changes: Change[]) { + private static normalize(changes: Change[]): Change[] { // order changes by start position const normalized = stableSort(changes, (a, b) => a.range.pos - b.range.pos); // verify that change intervals do not overlap, except possibly at end points. @@ -560,6 +560,8 @@ namespace ts.textChanges { public readonly onEmitNode: PrintHandlers["onEmitNode"]; public readonly onBeforeEmitNodeArray: PrintHandlers["onBeforeEmitNodeArray"]; public readonly onAfterEmitNodeArray: PrintHandlers["onAfterEmitNodeArray"]; + public readonly onBeforeEmitToken: PrintHandlers["onBeforeEmitToken"]; + public readonly onAfterEmitToken: PrintHandlers["onAfterEmitToken"]; constructor(newLine: string) { this.writer = createTextWriter(newLine); @@ -582,6 +584,16 @@ namespace ts.textChanges { setEnd(nodes, this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = node => { + if (node) { + setPos(node, this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = node => { + if (node) { + setEnd(node, this.lastNonTriviaPosition); + } + }; } private setLastNonTriviaPosition(s: string, force: boolean) { diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index fd7269d46dd..0c1d76e7ae5 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -64,35 +64,12 @@ "signatureHelp.ts", "symbolDisplay.ts", "textChanges.ts", - "formatting/formatting.ts", - "formatting/formattingContext.ts", - "formatting/formattingRequestKind.ts", - "formatting/formattingScanner.ts", - "formatting/references.ts", - "formatting/rule.ts", - "formatting/ruleAction.ts", - "formatting/ruleDescriptor.ts", - "formatting/ruleFlag.ts", - "formatting/ruleOperation.ts", - "formatting/ruleOperationContext.ts", - "formatting/rules.ts", - "formatting/rulesMap.ts", - "formatting/rulesProvider.ts", - "formatting/smartIndenter.ts", - "formatting/tokenRange.ts", - "codeFixProvider.ts", - "codefixes/fixAddMissingMember.ts", - "codefixes/fixSpelling.ts", - "codefixes/fixExtendsInterfaceBecomesImplements.ts", - "codefixes/fixClassIncorrectlyImplementsInterface.ts", - "codefixes/fixClassDoesntImplementInheritedAbstractMember.ts", - "codefixes/fixClassSuperMustPrecedeThisAccess.ts", - "codefixes/fixConstructorForDerivedNeedSuperCall.ts", - "codefixes/fixForgottenThisPropertyAccess.ts", - "codefixes/fixes.ts", - "codefixes/helpers.ts", - "codefixes/importFixes.ts", - "codefixes/unusedIdentifierFixes.ts", - "codefixes/disableJsDiagnostics.ts" + "refactorProvider.ts", + "codeFixProvider.ts" + ], + "include": [ + "formatting/*", + "codefixes/*", + "refactors/*" ] } diff --git a/src/services/types.ts b/src/services/types.ts index b1137bc4bc9..6c64ce5b9ba 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -261,6 +261,8 @@ namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; @@ -352,6 +354,11 @@ namespace ts { changes: FileTextChanges[]; } + export interface ApplicableRefactorInfo { + name: string; + description: string; + } + export interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ diff --git a/tests/cases/fourslash/convertFunctionToEs6Class1.ts b/tests/cases/fourslash/convertFunctionToEs6Class1.ts new file mode 100644 index 00000000000..6275e48e627 --- /dev/null +++ b/tests/cases/fourslash/convertFunctionToEs6Class1.ts @@ -0,0 +1,26 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: test123.js +//// [|function /*1*/foo() { } +//// /*2*/foo.prototype.instanceMethod1 = function() { return "this is name"; }; +//// /*3*/foo.prototype.instanceMethod2 = () => { return "this is name"; }; +//// /*4*/foo.prototype.instanceProp1 = "hello"; +//// /*5*/foo.prototype.instanceProp2 = undefined; +//// /*6*/foo.staticProp = "world"; +//// /*7*/foo.staticMethod1 = function() { return "this is static name"; }; +//// /*8*/foo.staticMethod2 = () => "this is static name";|] + +['1', '2', '3', '4', '5', '6', '7', '8'].forEach(m => verify.applicableRefactorAvailableAtMarker(m)); +verify.fileAfterApplyingRefactorAtMarker('1', +`class foo { + constructor() { } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } + static staticMethod1() { return "this is static name"; } + static staticMethod2() { return "this is static name"; } +} +foo.prototype.instanceProp1 = "hello"; +foo.prototype.instanceProp2 = undefined; +foo.staticProp = "world"; +`, 'Convert to ES2015 class'); \ No newline at end of file diff --git a/tests/cases/fourslash/convertFunctionToEs6Class2.ts b/tests/cases/fourslash/convertFunctionToEs6Class2.ts new file mode 100644 index 00000000000..5d9a9f32585 --- /dev/null +++ b/tests/cases/fourslash/convertFunctionToEs6Class2.ts @@ -0,0 +1,27 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: test123.js +//// [|var /*1*/foo = function() { }; +//// /*2*/foo.prototype.instanceMethod1 = function() { return "this is name"; }; +//// /*3*/foo.prototype.instanceMethod2 = () => { return "this is name"; }; +//// /*4*/foo.instanceProp1 = "hello"; +//// /*5*/foo.instanceProp2 = undefined; +//// /*6*/foo.staticProp = "world"; +//// /*7*/foo.staticMethod1 = function() { return "this is static name"; }; +//// /*8*/foo.staticMethod2 = () => "this is static name";|] + + +['1', '2', '3', '4', '5', '6', '7', '8'].forEach(m => verify.applicableRefactorAvailableAtMarker(m)); +verify.fileAfterApplyingRefactorAtMarker('4', +`class foo { + constructor() { } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } + static staticMethod1() { return "this is static name"; } + static staticMethod2() { return "this is static name"; } +} +foo.instanceProp1 = "hello"; +foo.instanceProp2 = undefined; +foo.staticProp = "world"; +`, 'Convert to ES2015 class'); diff --git a/tests/cases/fourslash/convertFunctionToEs6Class3.ts b/tests/cases/fourslash/convertFunctionToEs6Class3.ts new file mode 100644 index 00000000000..af8955dcb71 --- /dev/null +++ b/tests/cases/fourslash/convertFunctionToEs6Class3.ts @@ -0,0 +1,28 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: test123.js +//// [|var bar = 10, /*1*/foo = function() { }; +//// /*2*/foo.prototype.instanceMethod1 = function() { return "this is name"; }; +//// /*3*/foo.prototype.instanceMethod2 = () => { return "this is name"; }; +//// /*4*/foo.prototype.instanceProp1 = "hello"; +//// /*5*/foo.prototype.instanceProp2 = undefined; +//// /*6*/foo.staticProp = "world"; +//// /*7*/foo.staticMethod1 = function() { return "this is static name"; }; +//// /*8*/foo.staticMethod2 = () => "this is static name";|] + + +['1', '2', '3', '4', '5', '6', '7', '8'].forEach(m => verify.applicableRefactorAvailableAtMarker(m)); +verify.fileAfterApplyingRefactorAtMarker('7', +`var bar = 10; +class foo { + constructor() { } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } + static staticMethod1() { return "this is static name"; } + static staticMethod2() { return "this is static name"; } +} +foo.prototype.instanceProp1 = "hello"; +foo.prototype.instanceProp2 = undefined; +foo.staticProp = "world"; +`, 'Convert to ES2015 class'); \ No newline at end of file diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 31d8b8b4ef2..3fada673f35 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -150,6 +150,9 @@ declare namespace FourSlashInterface { implementationListIsEmpty(): void; isValidBraceCompletionAtPosition(openingBrace?: string): void; codeFixAvailable(): void; + applicableRefactorAvailableAtMarker(markerName: string): void; + codeFixDiagnosticsAvailableAtMarkers(markerNames: string[], diagnosticCode?: number): void; + applicableRefactorAvailableForRange(): void; } class verify extends verifyNegatable { assertHasRanges(ranges: Range[]): void; @@ -234,6 +237,7 @@ declare namespace FourSlashInterface { DocCommentTemplate(expectedText: string, expectedOffset: number, empty?: boolean): void; noDocCommentTemplate(): void; rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void; + fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, formattingOptions?: FormatCodeOptions): void; importFixAtPosition(expectedTextArray: string[], errorCode?: number): void; navigationBar(json: any): void; diff --git a/tests/cases/fourslash/server/convertFunctionToEs6Class-server.ts b/tests/cases/fourslash/server/convertFunctionToEs6Class-server.ts new file mode 100644 index 00000000000..9ab47086f20 --- /dev/null +++ b/tests/cases/fourslash/server/convertFunctionToEs6Class-server.ts @@ -0,0 +1,25 @@ +// @allowNonTsExtensions: true +// @Filename: test123.js + +/// + +//// // Comment +//// function fn() { +//// this.baz = 10; +//// } +//// /*1*/fn.prototype.bar = function () { +//// console.log('hello world'); +//// } + +verify.applicableRefactorAvailableAtMarker('1'); +verify.fileAfterApplyingRefactorAtMarker('1', +`// Comment +class fn { + constructor() { + this.baz = 10; + } + bar() { + console.log('hello world'); + } +} +`, 'Convert to ES2015 class'); From 8db58bbd69a9328ced57186af37689d5c89cd445 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Fri, 19 May 2017 13:19:18 -0700 Subject: [PATCH 245/282] Make getNameOfDeclaration public --- src/compiler/utilities.ts | 60 +++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 6f99a71ab31..cccabded02a 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1776,36 +1776,6 @@ namespace ts { } } - export function getNameOfDeclaration(declaration: Declaration): DeclarationName { - if (!declaration) { - return undefined; - } - if (declaration.kind === SyntaxKind.BinaryExpression) { - const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression); - const lhs = (declaration as BinaryExpression).left; - switch (kind) { - case SpecialPropertyAssignmentKind.None: - case SpecialPropertyAssignmentKind.ModuleExports: - return undefined; - case SpecialPropertyAssignmentKind.ExportsProperty: - if (lhs.kind === SyntaxKind.Identifier) { - return (lhs as PropertyAccessExpression).name; - } - else { - return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; - } - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - return (lhs as PropertyAccessExpression).name; - case SpecialPropertyAssignmentKind.PrototypeProperty: - return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; - } - } - else { - return (declaration as NamedDeclaration).name; - } - } - export function isLiteralComputedPropertyDeclarationName(node: Node) { return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) && node.parent.kind === SyntaxKind.ComputedPropertyName && @@ -4729,4 +4699,34 @@ namespace ts { export function unescapeIdentifier(identifier: string): string { return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier; } + + export function getNameOfDeclaration(declaration: Declaration): DeclarationName { + if (!declaration) { + return undefined; + } + if (declaration.kind === SyntaxKind.BinaryExpression) { + const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression); + const lhs = (declaration as BinaryExpression).left; + switch (kind) { + case SpecialPropertyAssignmentKind.None: + case SpecialPropertyAssignmentKind.ModuleExports: + return undefined; + case SpecialPropertyAssignmentKind.ExportsProperty: + if (lhs.kind === SyntaxKind.Identifier) { + return (lhs as PropertyAccessExpression).name; + } + else { + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + case SpecialPropertyAssignmentKind.ThisProperty: + case SpecialPropertyAssignmentKind.Property: + return (lhs as PropertyAccessExpression).name; + case SpecialPropertyAssignmentKind.PrototypeProperty: + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + } + else { + return (declaration as NamedDeclaration).name; + } + } } From 6c4e747295c65fed3d00efaf9c17a46deaa7271d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Fri, 19 May 2017 14:13:33 -0700 Subject: [PATCH 246/282] Add `undefined` to return of getNameOfDeclaration --- src/compiler/utilities.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index cccabded02a..64f5445d3df 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4700,7 +4700,7 @@ namespace ts { return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier; } - export function getNameOfDeclaration(declaration: Declaration): DeclarationName { + export function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined { if (!declaration) { return undefined; } From c70fa1e573b388019352c915989ff45a19480eac Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Fri, 19 May 2017 15:08:24 -0700 Subject: [PATCH 247/282] Remove incorrect code in getNameOfDeclaration --- src/compiler/utilities.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 64f5445d3df..aaf9fdd97f3 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4712,12 +4712,6 @@ namespace ts { case SpecialPropertyAssignmentKind.ModuleExports: return undefined; case SpecialPropertyAssignmentKind.ExportsProperty: - if (lhs.kind === SyntaxKind.Identifier) { - return (lhs as PropertyAccessExpression).name; - } - else { - return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; - } case SpecialPropertyAssignmentKind.ThisProperty: case SpecialPropertyAssignmentKind.Property: return (lhs as PropertyAccessExpression).name; From 3c6393afe1b60cf10c6fef72cd39089e9f7927dc Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Fri, 19 May 2017 15:18:26 -0700 Subject: [PATCH 248/282] More fix+cleanup in getNameOfDeclaration --- src/compiler/utilities.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index aaf9fdd97f3..2a2fcd3820e 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4705,18 +4705,15 @@ namespace ts { return undefined; } if (declaration.kind === SyntaxKind.BinaryExpression) { - const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression); - const lhs = (declaration as BinaryExpression).left; - switch (kind) { - case SpecialPropertyAssignmentKind.None: - case SpecialPropertyAssignmentKind.ModuleExports: - return undefined; + const expr = declaration as BinaryExpression; + switch (getSpecialPropertyAssignmentKind(expr)) { case SpecialPropertyAssignmentKind.ExportsProperty: case SpecialPropertyAssignmentKind.ThisProperty: case SpecialPropertyAssignmentKind.Property: - return (lhs as PropertyAccessExpression).name; case SpecialPropertyAssignmentKind.PrototypeProperty: - return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + return (expr.left as PropertyAccessExpression).name; + default: + return undefined; } } else { From 226b2ef08742ac3500a744b5c65563c2eca10afe Mon Sep 17 00:00:00 2001 From: Blaine Bublitz Date: Fri, 19 May 2017 15:20:31 -0700 Subject: [PATCH 249/282] Fix updateTypeAliasDeclaration call --- src/compiler/visitor.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index eb28721a142..af18a5620c6 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -700,6 +700,8 @@ namespace ts { case SyntaxKind.TypeAliasDeclaration: return updateTypeAliasDeclaration(node, + nodesVisitor((node).decorators, visitor, isDecorator), + nodesVisitor((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isIdentifier), nodesVisitor((node).typeParameters, visitor, isTypeParameter), visitNode((node).type, visitor, isTypeNode)); From b162097c3c7f5e5174eb70124de8888669775dbd Mon Sep 17 00:00:00 2001 From: andy-ms Date: Fri, 19 May 2017 20:06:08 -0700 Subject: [PATCH 250/282] Make ScriptElementKind and HighlightSpanKind string enums --- lib/cancellationToken.js | 2 + lib/lib.d.ts | 48 +- lib/lib.es2015.iterable.d.ts | 78 +- lib/lib.es2015.proxy.d.ts | 2 +- lib/lib.es2016.full.d.ts | 1824 ++++++++ lib/lib.es2017.full.d.ts | 1824 ++++++++ lib/lib.es2017.sharedmemory.d.ts | 93 +- lib/lib.es5.d.ts | 48 +- lib/lib.es6.d.ts | 128 +- lib/lib.esnext.full.d.ts | 1824 ++++++++ lib/tsc.js | 5495 +++++++++++++++------- lib/tsserver.js | 6530 +++++++++++++++----------- lib/tsserverlibrary.d.ts | 320 +- lib/tsserverlibrary.js | 6516 +++++++++++++++----------- lib/typescript.d.ts | 279 +- lib/typescript.js | 7149 +++++++++++++++++------------ lib/typescriptServices.d.ts | 279 +- lib/typescriptServices.js | 7149 +++++++++++++++++------------ lib/typingsInstaller.js | 1245 ++++- src/server/client.ts | 12 +- src/server/protocol.ts | 19 +- src/services/findAllReferences.ts | 6 +- src/services/goToDefinition.ts | 18 +- src/services/navigateTo.ts | 2 +- src/services/pathCompletions.ts | 2 +- src/services/rename.ts | 2 +- src/services/symbolDisplay.ts | 4 +- src/services/types.ts | 108 +- src/services/utilities.ts | 4 +- 29 files changed, 27635 insertions(+), 13375 deletions(-) diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index 0e37b0689e0..ec9453bb00c 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -69,3 +69,5 @@ function createCancellationToken(args) { } } module.exports = createCancellationToken; + +//# sourceMappingURL=cancellationToken.js.map diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 80e09b844cb..9848b920637 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 1fe1a0e0ca1..551698607ca 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -52,17 +52,17 @@ interface Array { [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -86,21 +86,21 @@ interface ArrayConstructor { } interface ReadonlyArray { - /** Iterator */ + /** Iterator of values in the array. */ [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -111,9 +111,42 @@ interface IArguments { } interface Map { + /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ values(): IterableIterator; } @@ -128,9 +161,40 @@ interface WeakMapConstructor { } interface Set { + /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ values(): IterableIterator; } diff --git a/lib/lib.es2015.proxy.d.ts b/lib/lib.es2015.proxy.d.ts index 29b12d91e24..440897038ef 100644 --- a/lib/lib.es2015.proxy.d.ts +++ b/lib/lib.es2015.proxy.d.ts @@ -23,7 +23,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 737357fef6d..a22ca2e9d80 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -21,6 +21,1830 @@ and limitations under the License. /// /// +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U): Array; + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: object, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: object | null): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string; + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + + +interface Generator extends Iterator { } + +interface GeneratorFunction { + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + new (...args: any[]): Generator; + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + (...args: any[]): Generator; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: Generator; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + (...args: string[]): GeneratorFunction; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator of values in the array. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: object): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + + from(arrayLike: Iterable): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; + + from(arrayLike: Iterable): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; + + from(arrayLike: Iterable): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + + from(arrayLike: Iterable): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + + from(arrayLike: Iterable): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + + from(arrayLike: Iterable): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + + from(arrayLike: Iterable): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + + from(arrayLike: Iterable): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + + from(arrayLike: Iterable): Float64Array; +} + + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface ProxyHandler { + getPrototypeOf? (target: T): object | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): object; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T; +} +declare var Proxy: ProxyConstructor; + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: object, propertyKey: PropertyKey): boolean; + function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: object): object; + function has(target: object, propertyKey: PropertyKey): boolean; + function isExtensible(target: object): boolean; + function ownKeys(target: object): Array; + function preventExtensions(target: object): boolean; + function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: object, proto: any): boolean; +} + + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string | number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + + ///////////////////////////// /// IE DOM APIs diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index dae59bc9ae3..d70049b1309 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -23,6 +23,1830 @@ and limitations under the License. /// /// +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U): Array; + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: object, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: object | null): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string; + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + + +interface Generator extends Iterator { } + +interface GeneratorFunction { + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + new (...args: any[]): Generator; + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + (...args: any[]): Generator; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: Generator; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + (...args: string[]): GeneratorFunction; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator of values in the array. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: object): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + + from(arrayLike: Iterable): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; + + from(arrayLike: Iterable): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; + + from(arrayLike: Iterable): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + + from(arrayLike: Iterable): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + + from(arrayLike: Iterable): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + + from(arrayLike: Iterable): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + + from(arrayLike: Iterable): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + + from(arrayLike: Iterable): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + + from(arrayLike: Iterable): Float64Array; +} + + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface ProxyHandler { + getPrototypeOf? (target: T): object | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): object; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T; +} +declare var Proxy: ProxyConstructor; + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: object, propertyKey: PropertyKey): boolean; + function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: object): object; + function has(target: object, propertyKey: PropertyKey): boolean; + function isExtensible(target: object): boolean; + function ownKeys(target: object): Array; + function preventExtensions(target: object): boolean; + function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: object, proto: any): boolean; +} + + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string | number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + + ///////////////////////////// /// IE DOM APIs diff --git a/lib/lib.es2017.sharedmemory.d.ts b/lib/lib.es2017.sharedmemory.d.ts index c0254f1dc2c..50a38686a90 100644 --- a/lib/lib.es2017.sharedmemory.d.ts +++ b/lib/lib.es2017.sharedmemory.d.ts @@ -43,5 +43,96 @@ interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; new (byteLength: number): SharedArrayBuffer; } +declare var SharedArrayBuffer: SharedArrayBufferConstructor; -declare var SharedArrayBuffer: SharedArrayBufferConstructor; \ No newline at end of file +interface ArrayBufferTypes { + SharedArrayBuffer: SharedArrayBuffer; +} + +interface Atomics { + /** + * Adds a value to the value at the given position in the array, returning the original value. + * Until this atomic operation completes, any other read or write operation against the array + * will block. + */ + add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores the bitwise AND of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or + * write operation against the array will block. + */ + and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Replaces the value at the given position in the array if the original value equals the given + * expected value, returning the original value. Until this atomic operation completes, any + * other read or write operation against the array will block. + */ + compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + + /** + * Replaces the value at the given position in the array, returning the original value. Until + * this atomic operation completes, any other read or write operation against the array will + * block. + */ + exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Returns a value indicating whether high-performance algorithms can use atomic operations + * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed + * array. + */ + isLockFree(size: number): boolean; + + /** + * Returns the value at the given position in the array. Until this atomic operation completes, + * any other read or write operation against the array will block. + */ + load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + + /** + * Stores the bitwise OR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores a value at the given position in the array, returning the new value. Until this + * atomic operation completes, any other read or write operation against the array will block. + */ + store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Subtracts a value from the value at the given position in the array, returning the original + * value. Until this atomic operation completes, any other read or write operation against the + * array will block. + */ + sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * If the value at the given position in the array is equal to the provided value, the current + * agent is put to sleep causing execution to suspend until the timeout expires (returning + * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns + * `"not-equal"`. + */ + wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; + + /** + * Wakes up sleeping agents that are waiting on the given index of the array, returning the + * number of agents that were awoken. + */ + wake(typedArray: Int32Array, index: number, count: number): number; + + /** + * Stores the bitwise XOR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + readonly [Symbol.toStringTag]: "Atomics"; +} + +declare var Atomics: Atomics; \ No newline at end of file diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 1d19198d1d1..f359e519ab1 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 76dc84306ed..4d2428a59ba 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4977,17 +4985,17 @@ interface Array { [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -5011,21 +5019,21 @@ interface ArrayConstructor { } interface ReadonlyArray { - /** Iterator */ + /** Iterator of values in the array. */ [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -5036,9 +5044,42 @@ interface IArguments { } interface Map { + /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ values(): IterableIterator; } @@ -5053,9 +5094,40 @@ interface WeakMapConstructor { } interface Set { + /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ values(): IterableIterator; } @@ -5637,7 +5709,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index d285df3f4db..70db6a78452 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -22,6 +22,1830 @@ and limitations under the License. /// +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U): Array; + from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: object, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: object | null): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; + find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean): number; + findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; + findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string; + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + + +interface Generator extends Iterator { } + +interface GeneratorFunction { + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + new (...args: any[]): Generator; + /** + * Creates a new Generator object. + * @param args A list of arguments the function accepts. + */ + (...args: any[]): Generator; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: Generator; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + (...args: string[]): GeneratorFunction; + /** + * The length of the arguments. + */ + readonly length: number; + /** + * Returns the name of the function. + */ + readonly name: string; + /** + * A reference to the prototype. + */ + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; + from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; + from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator of values in the array. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an iterable of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: object): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + + from(arrayLike: Iterable): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; + + from(arrayLike: Iterable): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; + + from(arrayLike: Iterable): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + + from(arrayLike: Iterable): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + + from(arrayLike: Iterable): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + + from(arrayLike: Iterable): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + + from(arrayLike: Iterable): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + + from(arrayLike: Iterable): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; + from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; + from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + + from(arrayLike: Iterable): Float64Array; +} + + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface ProxyHandler { + getPrototypeOf? (target: T): object | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): object; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T; +} +declare var Proxy: ProxyConstructor; + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: object, propertyKey: PropertyKey): boolean; + function get(target: object, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: object): object; + function has(target: object, propertyKey: PropertyKey): boolean; + function isExtensible(target: object): boolean; + function ownKeys(target: object): Array; + function preventExtensions(target: object): boolean; + function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: object, proto: any): boolean; +} + + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string | number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + + ///////////////////////////// /// IE DOM APIs diff --git a/lib/tsc.js b/lib/tsc.js index 693a32dc98b..1d92d339b9d 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -15,12 +15,449 @@ and limitations under the License. var ts; (function (ts) { + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 126] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 127] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 128] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 129] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 130] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 131] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 132] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 133] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 134] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 135] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 136] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; + SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; + SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; + SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; + SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; + SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 270] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 271] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 272] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 273] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 274] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 275] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 276] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 277] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 278] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 279] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 280] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 281] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 282] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 284] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 285] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 286] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 287] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 288] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 289] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 290] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 291] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 293] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 283] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + var GeneratedIdentifierKind; + (function (GeneratedIdentifierKind) { + GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; + })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var NumericLiteralFlags; + (function (NumericLiteralFlags) { + NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; + NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; + NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; + NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; + NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; + })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -30,13 +467,60 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 2] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 4] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 8] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 16] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 2048] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 4096] = "AddUndefined"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -51,6 +535,196 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; + SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; + SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 16777216] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 33554432] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 67108864] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 134217728] = "Transient"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["Void"] = 1024] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 4096] = "Null"; + TypeFlags[TypeFlags["Never"] = 8192] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 32768] = "Object"; + TypeFlags[TypeFlags["Union"] = 65536] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 262144] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; + TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; + TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; + TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; + TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var SpecialPropertyAssignmentKind; + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -71,6 +745,179 @@ var ts; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var DiagnosticStyle; + (function (DiagnosticStyle) { + DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; + DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; + })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { Extension[Extension["Ts"] = 0] = "Ts"; @@ -80,6 +927,126 @@ var ts; Extension[Extension["Jsx"] = 4] = "Jsx"; Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; })(Extension = ts.Extension || (ts.Extension = {})); + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -145,6 +1112,12 @@ var ts; ts.version = "2.4.0"; })(ts || (ts = {})); (function (ts) { + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { @@ -278,6 +1251,12 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -315,6 +1294,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -519,6 +1507,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1543,6 +2553,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -1811,6 +2825,13 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -1895,6 +2916,13 @@ var ts; getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } }; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -2214,6 +3242,11 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); function fileSystemEntryExists(path, entryKind) { try { var stat = _fs.statSync(path); @@ -2579,6 +3612,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2686,7 +3720,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -2881,6 +3915,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3176,6 +4218,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -3221,6 +4264,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3302,6 +4347,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -3850,9 +4898,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -4982,9 +6031,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -5141,26 +6188,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5367,10 +6416,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -5622,6 +6667,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -5846,6 +6900,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -6318,6 +7376,12 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { @@ -6393,21 +7457,46 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -6507,21 +7596,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -6544,7 +7631,18 @@ var ts; return 2 <= token && token <= 7; } ts.isTrivia = isTrivia; + var FunctionFlags; + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; + FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; + FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; + FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; + })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6589,7 +7687,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -6698,6 +7797,11 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + var Associativity; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); var hasArguments = expression.kind === 182 && expression.arguments !== undefined; @@ -6859,6 +7963,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -6962,12 +8068,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -7056,7 +8163,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -7108,7 +8215,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -7597,13 +8704,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -7851,10 +8958,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -7922,9 +9025,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -8122,6 +9236,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8208,6 +9323,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -8230,6 +9349,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -8301,8 +9424,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8418,6 +9541,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -8756,15 +9921,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -8852,237 +10026,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -9093,42 +10042,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -9165,6 +10078,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -9186,7 +10119,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -9199,7 +10149,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -9209,7 +10159,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -9277,6 +10227,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -9322,9 +10515,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -9337,9 +10529,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -9387,9 +10578,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -9579,10 +10770,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -9709,6 +10900,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -9723,6 +10927,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -9732,7 +10940,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -9752,35 +10960,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -9999,6 +11178,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -10047,6 +11259,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -10067,7 +11321,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -10108,6 +11362,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -10138,7 +11404,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -10324,19 +11591,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -10351,6 +11605,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -10376,20 +11642,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -10398,10 +11650,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -10411,12 +11663,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -10425,10 +11689,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -10440,10 +11704,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -10454,10 +11718,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -10467,10 +11731,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -10565,14 +11828,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -10593,6 +11856,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -10903,6 +12189,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -11143,7 +12448,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -11250,9 +12557,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -11363,16 +12671,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -11541,6 +12839,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -11580,6 +12906,13 @@ var ts; return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; + 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 = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7; } var previousNode; @@ -11686,7 +13019,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -12343,6 +13676,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -16204,6 +17539,43 @@ var ts; : undefined; }); } + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; + ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["JSDocFunctionParameters"] = 23] = "JSDocFunctionParameters"; + ParsingContext[ParsingContext["JSDocTypeArguments"] = 24] = "JSDocTypeArguments"; + ParsingContext[ParsingContext["JSDocRecordMembers"] = 25] = "JSDocRecordMembers"; + ParsingContext[ParsingContext["JSDocTupleTypes"] = 26] = "JSDocTupleTypes"; + ParsingContext[ParsingContext["Count"] = 27] = "Count"; + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function isJSDocType() { @@ -16500,6 +17872,12 @@ var ts; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -16642,6 +18020,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -17296,10 +18676,20 @@ var ts; } } } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); var ts; (function (ts) { + var ModuleInstanceState; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { if (node.kind === 230 || node.kind === 231) { return 0; @@ -17338,6 +18728,18 @@ var ts; } } ts.getModuleInstanceState = getModuleInstanceState; + var ContainerFlags; + (function (ContainerFlags) { + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; + ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; + })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -17380,7 +18782,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -17408,7 +18810,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -17441,19 +18843,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -17549,9 +18952,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -18575,6 +19978,11 @@ var ts; typeLiteralSymbol.members.set(symbol.name, symbol); } function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); if (inStrictMode) { var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { @@ -19196,7 +20604,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -19211,7 +20619,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19226,7 +20634,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19239,7 +20647,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19965,12 +21373,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -20254,6 +21661,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -20387,12 +21796,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -20422,7 +21837,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -20741,6 +22155,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -20885,13 +22300,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -20964,11 +22382,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -20982,6 +22402,66 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); + var TypeFacts; + (function (TypeFacts) { + TypeFacts[TypeFacts["None"] = 0] = "None"; + TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; + TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; + TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; + TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; + TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; + TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; + TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; + TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; + TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; + TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; + TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; + TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; + TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; + TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; + TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; + TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; + TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; + TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; + TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; + TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; + TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; + TypeFacts[TypeFacts["All"] = 8388607] = "All"; + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; + TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; + TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; + TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; + TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; + TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; + TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; + TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; + TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; + TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; + TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; + TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ "string": 1, "number": 2, @@ -21031,6 +22511,19 @@ var ts; var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); var _displayBuilder; + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var CheckMode; + (function (CheckMode) { + CheckMode[CheckMode["Normal"] = 0] = "Normal"; + CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createMap(); builtinGlobals.set(undefinedSymbol.name, undefinedSymbol); initializeTypeChecker(); @@ -21152,16 +22645,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -21234,9 +22727,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -21244,7 +22734,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -21272,7 +22762,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -21347,7 +22838,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -21356,7 +22851,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -21403,12 +22898,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -21417,7 +22912,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -21426,7 +22921,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -21448,7 +22943,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -21495,7 +22990,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -21505,7 +23000,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -21602,6 +23107,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -21633,13 +23142,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -21651,7 +23160,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -21754,10 +23263,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -21773,7 +23282,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -21895,7 +23404,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -21915,6 +23424,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -21974,7 +23488,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -22115,7 +23628,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -22385,34 +23898,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -22422,12 +23960,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -22444,23 +23982,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -22480,8 +24020,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -22492,72 +24032,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -22565,12 +24086,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -22612,41 +24133,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -22654,7 +24186,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -22664,48 +24196,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -22714,74 +24270,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -22789,18 +24392,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -22809,20 +24412,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -22848,28 +24441,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -22887,12 +24481,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -22928,13 +24524,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -22977,7 +24574,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -23042,12 +24639,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -23384,7 +24984,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -23635,10 +25235,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -23759,7 +25356,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -23859,7 +25456,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -23937,6 +25534,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -23953,16 +25551,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -24172,7 +25777,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -24228,7 +25833,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -24404,11 +26009,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -24572,77 +26178,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -24874,7 +26483,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -24951,8 +26560,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -25096,7 +26705,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -25216,6 +26825,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -25272,8 +26902,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -25315,7 +26945,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -25329,12 +26959,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -25400,7 +27030,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -25763,8 +27393,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -25891,8 +27522,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -25922,7 +27553,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -25934,7 +27565,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -25954,7 +27585,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -25966,7 +27597,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -26003,14 +27633,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -26069,16 +27700,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -26300,14 +27931,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -26315,8 +27946,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -26437,8 +28068,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -26489,9 +28120,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -26521,12 +28152,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -26541,11 +28172,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -26570,7 +28201,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -26702,7 +28333,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -26719,11 +28350,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -26750,15 +28381,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -26769,11 +28401,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -27028,7 +28662,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -27439,29 +29073,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -27472,42 +29104,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -27691,24 +29328,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -28057,10 +29676,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -28157,23 +29776,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -28284,7 +29914,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -28307,11 +29937,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -28350,8 +29980,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -28429,8 +30059,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -28438,8 +30068,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -28462,7 +30092,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -28502,27 +30132,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -28530,43 +30160,43 @@ 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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -28711,7 +30341,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -28788,7 +30418,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -28821,20 +30451,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -28847,7 +30467,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -28935,26 +30555,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -29037,8 +30656,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -29113,7 +30732,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -29123,7 +30742,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -29188,7 +30807,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -29248,8 +30867,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -29265,15 +30884,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -29475,7 +31095,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -29498,8 +31118,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -29568,8 +31188,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -29595,7 +31215,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -29621,7 +31241,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -29741,7 +31361,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -30174,6 +31794,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -30228,7 +31864,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -30258,12 +31894,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -30958,8 +32594,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -31050,7 +32686,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -31065,7 +32701,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -31203,6 +32839,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -31262,6 +32900,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -31279,6 +32921,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -31288,37 +32933,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -31328,9 +32973,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -31340,11 +32984,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -31399,7 +33047,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -31433,6 +33092,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -31442,6 +33115,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -31467,6 +33141,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -31512,7 +33187,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -31670,6 +33345,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -31681,7 +33374,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -31699,36 +33401,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -31803,42 +33487,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -31874,7 +33522,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -31890,6 +33538,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -31997,7 +33746,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -32020,8 +33775,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -32108,7 +33863,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -32344,7 +34099,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -32422,7 +34177,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -32450,7 +34205,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -32491,25 +34246,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -32519,14 +34305,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -32657,7 +34435,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -32784,8 +34562,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -32929,7 +34707,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -32993,10 +34771,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -33280,15 +35058,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -33368,7 +35146,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -33411,8 +35189,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33426,8 +35204,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -33436,8 +35214,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -33472,7 +35250,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -33744,7 +35522,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -33798,7 +35576,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -33880,12 +35658,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -33925,9 +35703,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -33981,7 +35759,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -34278,17 +36056,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -34311,7 +36086,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -34334,6 +36109,13 @@ var ts; } } function checkClassForDuplicateDeclarations(node) { + var Declaration; + (function (Declaration) { + Declaration[Declaration["Getter"] = 1] = "Getter"; + Declaration[Declaration["Setter"] = 2] = "Setter"; + Declaration[Declaration["Method"] = 4] = "Method"; + Declaration[Declaration["Property"] = 3] = "Property"; + })(Declaration || (Declaration = {})); var instanceNames = ts.createMap(); var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { @@ -34425,7 +36207,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -34499,7 +36281,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -34637,7 +36420,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -34676,7 +36459,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -34726,16 +36509,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -34746,7 +36529,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -34854,7 +36637,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -34867,8 +36650,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -34917,11 +36700,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -35117,7 +36901,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -35127,6 +36913,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -35153,7 +36976,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -35162,15 +36985,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -35283,15 +37106,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -35369,7 +37193,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -35431,7 +37255,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -35445,7 +37269,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -35641,7 +37465,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -35747,11 +37571,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -36201,11 +38026,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -36420,7 +38248,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -36439,7 +38267,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -36454,13 +38282,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -36479,7 +38304,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -36562,88 +38387,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -36656,75 +38474,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -36747,7 +38543,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -36972,6 +38768,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -37618,7 +39417,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -37731,7 +39530,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -37793,16 +39592,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -38063,7 +39862,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -38091,7 +39890,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -38103,15 +39902,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -38190,7 +39980,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -38337,7 +40126,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -38364,9 +40153,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -39395,6 +41185,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -39505,49 +41306,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -39558,20 +41369,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -39608,12 +41405,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -39630,6 +41427,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -39674,6 +41473,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -39682,6 +41485,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -39706,8 +41511,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -39716,6 +41519,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -39740,6 +41545,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -39795,6 +41602,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -40133,6 +41947,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -40231,6 +42048,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; var value; @@ -40550,6 +42372,12 @@ var ts; var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -40572,7 +42400,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -41361,15 +43189,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -41656,7 +43479,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -41703,9 +43531,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -41838,7 +43666,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -42130,6 +43958,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; var resolver = context.getEmitResolver(); @@ -42144,7 +43976,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -42371,6 +44203,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var ESNextSubstitutionFlags; + (function (ESNextSubstitutionFlags) { + ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); function transformESNext(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -42385,7 +44221,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -42453,19 +44289,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -42592,6 +44423,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -42599,19 +44433,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -42620,12 +44452,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -42857,12 +44684,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -42874,11 +44711,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -42897,7 +44734,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -43335,7 +45172,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -43393,6 +45230,75 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; + HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; + HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; + HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; + HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; + HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; + HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; + HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; + HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; + HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; + HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; + HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; + HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; + HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; + HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; + HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; + HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; + HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); @@ -43408,7 +45314,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -44271,12 +46177,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -45164,7 +47071,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -45313,6 +47220,51 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; + })(OpCode || (OpCode = {})); + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); function getInstructionName(instruction) { switch (instruction) { case 2: return "return"; @@ -45357,8 +47309,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -46974,7 +48925,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -47137,9 +49088,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -47643,9 +49594,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -48158,9 +50107,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -48451,7 +50400,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -48522,6 +50471,18 @@ var ts; return ts.transformModule; } } + var TransformationState; + (function (TransformationState) { + TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; + TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; + TransformationState[TransformationState["Completed"] = 2] = "Completed"; + TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; + })(TransformationState || (TransformationState = {})); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); function getTransformers(compilerOptions, customTransformers) { var jsx = compilerOptions.jsx; var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -48554,7 +50515,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -48612,7 +50573,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -49387,7 +51348,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -49412,11 +51373,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -49820,8 +51781,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -49834,23 +51794,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -49860,12 +51827,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -49935,7 +51896,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50163,7 +52124,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -50260,7 +52221,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50272,12 +52233,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -50291,7 +52246,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -50306,6 +52261,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -50313,15 +52281,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -50342,7 +52317,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -50394,7 +52369,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -50402,7 +52378,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -50597,6 +52573,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -50855,7 +52836,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -51013,7 +52994,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -51044,7 +53025,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -51130,7 +53111,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -51206,7 +53189,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -51406,7 +53389,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -51426,7 +53409,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -51488,6 +53471,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -51513,6 +53498,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -51535,6 +53521,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -51649,7 +53636,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -51687,9 +53676,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -51700,8 +53695,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -51714,7 +53714,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -51790,7 +53790,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -51881,7 +53881,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -52560,6 +54560,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -52808,6 +54811,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -52985,7 +54997,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -53164,6 +55178,77 @@ var ts; function getClosingBracket(format) { return brackets[format & 7680][1]; } + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -53352,6 +55437,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -53401,6 +55563,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -53443,7 +55606,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -53492,7 +55656,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -53525,45 +55690,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -53572,15 +55756,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -53599,67 +55780,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -53667,11 +55854,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -53683,8 +55875,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -54024,7 +56215,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -54055,7 +56246,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -54096,13 +56286,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -54125,45 +56315,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -54299,10 +56494,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -54351,7 +56546,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -54448,12 +56643,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -55536,49 +57731,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -55588,37 +57762,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -55649,9 +57793,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -55668,9 +57809,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -55915,8 +58113,8 @@ var ts; reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); } function reportDiagnostics(diagnostics, host) { - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; reportDiagnostic(diagnostic, host); } } @@ -55949,73 +58147,8 @@ var ts; function reportDiagnosticSimply(diagnostic, host) { ts.sys.write(ts.formatDiagnostics([diagnostic], host)); } - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; - var gutterSeparator = " "; - var resetEscapeSequence = "\u001b[0m"; - var ellipsis = "..."; - function getCategoryFormat(category) { - switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; - } - } - function formatAndReset(text, formatStyle) { - return formatStyle + text + resetEscapeSequence; - } function reportDiagnosticWithColorAndContext(diagnostic, host) { - var output = ""; - if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; - var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; - var gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - output += ts.sys.newLine; - for (var i = firstLine; i <= lastLine; i++) { - if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; - i = lastLine - 1; - } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); - lineContent = lineContent.replace("\t", " "); - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; - if (i === firstLine) { - var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - output += lineContent.replace(/./g, "~"); - } - output += resetEscapeSequence; - output += ts.sys.newLine; - } - output += ts.sys.newLine; - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; - } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine + ts.sys.newLine; - ts.sys.write(output); + ts.sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + ts.sys.newLine + ts.sys.newLine); } function reportWatchDiagnostic(diagnostic) { var output = new Date().toLocaleTimeString() + " - "; @@ -56482,3 +58615,5 @@ if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnviron ts.sys.tryEnableSourceMapsForHost(); } ts.executeCommandLine(ts.sys.args); + +//# sourceMappingURL=tsc.js.map diff --git a/lib/tsserver.js b/lib/tsserver.js index 05f4c1e5fd1..ae6c3c8dc07 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -332,9 +332,10 @@ var ts; SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -469,6 +470,12 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -478,12 +485,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -604,6 +619,11 @@ var ts; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -671,21 +691,21 @@ var ts; TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; @@ -1011,6 +1031,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1025,14 +1046,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1288,6 +1312,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1492,6 +1525,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -2516,6 +2571,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3571,6 +3630,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -3678,7 +3738,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -3873,6 +3933,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4168,6 +4236,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4213,6 +4282,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4294,6 +4365,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -4322,12 +4396,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -4611,6 +4684,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -4744,12 +4819,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -4779,7 +4860,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -5164,9 +5244,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -5323,26 +5401,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5549,10 +5629,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -5804,6 +5880,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -6028,6 +6113,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -6581,21 +6670,46 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -6695,21 +6809,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -6737,12 +6849,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6787,7 +6900,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -7062,6 +7176,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -7165,12 +7281,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -7259,7 +7376,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -7311,7 +7428,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -7800,13 +7917,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -8054,10 +8171,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -8125,9 +8238,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -8325,6 +8449,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8411,6 +8536,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -8433,6 +8562,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -8504,8 +8637,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8621,6 +8754,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9424,9 +9599,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -10536,15 +10712,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -10632,237 +10817,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -10873,42 +10833,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -10945,6 +10869,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -10966,7 +10910,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -10979,7 +10940,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -10989,7 +10950,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11057,6 +11018,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -11102,9 +11306,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11117,9 +11320,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11167,9 +11369,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11359,10 +11561,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11489,6 +11691,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -11503,6 +11718,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -11512,7 +11731,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11532,35 +11751,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -11779,6 +11969,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -11827,6 +12050,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -11847,7 +12112,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -11888,6 +12153,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -11918,7 +12195,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12104,19 +12382,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -12131,6 +12396,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -12156,20 +12433,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12178,10 +12441,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12191,12 +12454,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12205,10 +12480,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -12220,10 +12495,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12234,10 +12509,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12247,10 +12522,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -12345,14 +12619,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -12373,6 +12647,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -12683,6 +12980,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -12923,7 +13239,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13030,9 +13348,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -13143,16 +13462,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -13321,6 +13630,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -13473,7 +13810,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -14130,6 +14467,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -18472,6 +18811,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -19232,7 +19573,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -19260,7 +19601,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -19293,19 +19634,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -19401,9 +19743,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -21053,7 +21395,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -21068,7 +21410,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21083,7 +21425,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21096,7 +21438,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21831,6 +22173,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -21975,13 +22318,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -22054,11 +22400,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -22315,16 +22663,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -22397,9 +22745,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -22407,7 +22752,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -22435,7 +22780,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -22510,7 +22856,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -22519,7 +22869,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -22566,12 +22916,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -22580,7 +22930,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -22589,7 +22939,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -22611,7 +22961,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -22658,7 +23008,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -22668,7 +23018,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -22765,6 +23125,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -22796,13 +23160,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -22814,7 +23178,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -22917,10 +23281,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -22936,7 +23300,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -23058,7 +23422,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -23078,6 +23442,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -23137,7 +23506,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -23278,7 +23646,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -23548,34 +23916,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -23585,12 +23978,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -23607,23 +24000,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -23643,8 +24038,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -23655,72 +24050,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -23728,12 +24104,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -23775,41 +24151,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -23817,7 +24204,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -23827,48 +24214,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -23877,74 +24288,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -23952,18 +24410,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -23972,20 +24430,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -24011,28 +24459,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -24050,12 +24499,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -24091,13 +24542,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -24140,7 +24592,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -24205,12 +24657,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -24547,7 +25002,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -24798,10 +25253,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -24922,7 +25374,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -25022,7 +25474,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -25100,6 +25552,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -25116,16 +25569,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -25335,7 +25795,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -25391,7 +25851,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -25567,11 +26027,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -25735,77 +26196,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -26037,7 +26501,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -26114,8 +26578,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -26259,7 +26723,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -26379,6 +26843,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -26435,8 +26920,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -26478,7 +26963,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -26492,12 +26977,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -26563,7 +27048,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -26926,8 +27411,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -27054,8 +27540,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -27085,7 +27571,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -27097,7 +27583,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -27117,7 +27603,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -27129,7 +27615,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -27166,14 +27651,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -27232,16 +27718,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -27463,14 +27949,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -27478,8 +27964,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -27600,8 +28086,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -27652,9 +28138,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -27684,12 +28170,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -27704,11 +28190,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -27733,7 +28219,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -27865,7 +28351,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -27882,11 +28368,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -27913,15 +28399,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -27932,11 +28419,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -28191,7 +28680,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -28602,29 +29091,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -28635,42 +29122,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -28854,24 +29346,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -29220,10 +29694,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -29320,23 +29794,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -29447,7 +29932,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -29470,11 +29955,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -29513,8 +29998,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -29592,8 +30077,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -29601,8 +30086,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -29625,7 +30110,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -29665,27 +30150,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -29693,43 +30178,43 @@ 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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -29874,7 +30359,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -29951,7 +30436,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -29984,20 +30469,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -30010,7 +30485,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -30098,26 +30573,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -30200,8 +30674,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -30276,7 +30750,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -30286,7 +30760,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -30351,7 +30825,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -30411,8 +30885,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -30428,15 +30902,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -30638,7 +31113,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -30661,8 +31136,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30731,8 +31206,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -30758,7 +31233,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -30784,7 +31259,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -30904,7 +31379,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -31337,6 +31812,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -31391,7 +31882,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -31421,12 +31912,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -32121,8 +32612,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -32213,7 +32704,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -32228,7 +32719,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -32366,6 +32857,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -32425,6 +32918,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -32442,6 +32939,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -32451,37 +32951,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -32491,9 +32991,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -32503,11 +33002,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -32562,7 +33065,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -32596,6 +33110,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -32605,6 +33133,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -32630,6 +33159,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -32675,7 +33205,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -32833,6 +33363,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -32844,7 +33392,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -32862,36 +33419,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -32966,42 +33505,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -33037,7 +33540,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -33053,6 +33556,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -33160,7 +33764,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -33183,8 +33793,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -33271,7 +33881,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -33507,7 +34117,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -33585,7 +34195,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -33613,7 +34223,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -33654,25 +34264,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -33682,14 +34323,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -33820,7 +34453,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -33947,8 +34580,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -34092,7 +34725,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -34156,10 +34789,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -34443,15 +35076,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -34531,7 +35164,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -34574,8 +35207,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -34589,8 +35222,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -34599,8 +35232,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -34635,7 +35268,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -34907,7 +35540,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -34961,7 +35594,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -35043,12 +35676,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -35088,9 +35721,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -35144,7 +35777,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -35441,17 +36074,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -35474,7 +36104,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -35595,7 +36225,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -35669,7 +36299,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -35807,7 +36438,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -35846,7 +36477,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -35896,16 +36527,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -35916,7 +36547,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -36024,7 +36655,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -36037,8 +36668,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -36087,11 +36718,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -36287,7 +36919,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -36297,6 +36931,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -36323,7 +36994,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -36332,15 +37003,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -36453,15 +37124,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -36539,7 +37211,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -36601,7 +37273,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -36615,7 +37287,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -36811,7 +37483,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -36917,11 +37589,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -37371,11 +38044,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -37590,7 +38266,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -37609,7 +38285,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -37624,13 +38300,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -37649,7 +38322,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -37732,88 +38405,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -37826,75 +38492,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -37917,7 +38561,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -38142,6 +38786,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -38788,7 +39435,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -38901,7 +39548,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -38963,16 +39610,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -39233,7 +39880,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -39261,7 +39908,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -39273,15 +39920,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -39360,7 +39998,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -39507,7 +40144,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -39534,9 +40171,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -40565,6 +41203,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -40675,49 +41324,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -40728,20 +41387,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -40778,12 +41423,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -40800,6 +41445,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -40844,6 +41491,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -40852,6 +41503,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -40876,8 +41529,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -40886,6 +41537,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -40910,6 +41563,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -40965,6 +41620,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -41303,6 +41965,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -41753,7 +42418,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -42542,15 +43207,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -42837,7 +43497,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -42884,9 +43549,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -43019,7 +43684,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -43329,7 +43994,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -43574,7 +44239,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -43642,19 +44307,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -43781,6 +44441,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -43788,19 +44451,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -43809,12 +44470,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -44046,12 +44702,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -44063,11 +44729,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -44086,7 +44752,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -44524,7 +45190,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -44666,7 +45332,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -45529,12 +46195,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -46422,7 +47089,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -46590,8 +47257,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -48277,7 +48943,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -48440,9 +49106,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -48946,9 +49612,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -49461,9 +50125,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -49754,7 +50418,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -49869,7 +50533,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -49927,7 +50591,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -50097,7 +50761,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -50122,11 +50786,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -50530,8 +51194,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -50544,23 +51207,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -50570,12 +51240,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -50645,7 +51309,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50873,7 +51537,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -50970,7 +51634,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50982,12 +51646,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -51001,7 +51659,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -51016,6 +51674,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -51023,15 +51694,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -51052,7 +51730,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -51104,7 +51782,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -51112,7 +51791,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -51307,6 +51986,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -51565,7 +52249,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -52328,7 +53012,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -52359,7 +53043,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -52445,7 +53129,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -52521,7 +53207,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -52721,7 +53407,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -52741,7 +53427,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -52803,6 +53489,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -52828,6 +53516,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -52850,6 +53539,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -52964,7 +53654,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -53002,9 +53694,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -53015,8 +53713,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -53029,7 +53732,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -53105,7 +53808,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -53196,7 +53899,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -53875,6 +54578,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -54123,6 +54829,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -54300,7 +55015,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -54514,14 +55231,17 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -54735,6 +55455,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -54784,6 +55581,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -54826,7 +55624,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -54875,7 +55674,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -54908,45 +55708,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -54955,15 +55774,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -54982,67 +55798,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -55050,11 +55872,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -55066,8 +55893,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -55407,7 +56233,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -55438,7 +56264,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -55479,13 +56304,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -55508,45 +56333,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -55682,10 +56512,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -55734,7 +56564,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -55831,12 +56661,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -56919,49 +57749,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -56971,37 +57780,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -57032,9 +57811,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -57051,9 +57827,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -57509,7 +58342,6 @@ var ts; case 148: case 261: case 262: - case 264: case 151: case 150: case 152: @@ -57526,9 +58358,11 @@ var ts; case 231: case 163: return 2; + case 264: case 229: - case 232: return 1 | 2; + case 232: + return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -57545,7 +58379,7 @@ var ts; case 238: case 243: case 244: - return 1 | 2 | 4; + return 7; case 265: return 4 | 1; } @@ -57700,7 +58534,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -57715,31 +58549,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -58045,43 +58854,24 @@ var ts; if (ts.isToken(current)) { return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -58175,10 +58965,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; function isInsideJsxElementOrAttribute(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); if (!token) { @@ -58207,20 +58993,29 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end); }); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { + return kind === 2 || + !(text.charCodeAt(end - 1) === 47 && text.charCodeAt(end - 2) === 42); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); @@ -58336,6 +59131,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -58376,25 +59174,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119: @@ -58654,8 +59454,8 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; @@ -59202,7 +60002,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -59210,8 +60010,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60070,8 +60870,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -60328,7 +61128,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; } @@ -60352,13 +61152,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -60403,8 +61206,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -60461,10 +61264,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -60492,9 +61296,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -60502,16 +61307,20 @@ var ts; if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -60562,7 +61371,7 @@ var ts; var currentToken = ts.getTokenAtPosition(sourceFile, position); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -60592,7 +61401,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -60663,6 +61472,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -60693,7 +61503,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; @@ -60735,6 +61545,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -60742,6 +61553,10 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { @@ -60871,12 +61686,14 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174) { @@ -60893,7 +61710,10 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -60904,10 +61724,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -60933,6 +61749,42 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + isMemberCompletion = true; + isNewIdentifierLocation = true; + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32; + break; + } + } + if (!(classElementModifierFlags & 8)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -60961,6 +61813,37 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + case 26: + case 25: + case 18: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61050,7 +61933,7 @@ var ts; containingNodeKind === 231 || isFunction(containingNodeKind); case 115: - return containingNodeKind === 149; + return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: return containingNodeKind === 146 || (contextToken.parent && contextToken.parent.parent && @@ -61063,13 +61946,16 @@ var ts; return containingNodeKind === 242 || containingNodeKind === 246 || containingNodeKind === 240; + case 125: + case 135: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } case 75: case 83: case 109: case 89: case 104: - case 125: - case 135: case 91: case 110: case 76: @@ -61077,6 +61963,10 @@ var ts; case 138: return true; } + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61108,7 +61998,7 @@ var ts; var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -61134,7 +62024,7 @@ var ts; m.kind !== 154) { continue; } - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -61144,17 +62034,51 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + if (m.kind !== 149 && + m.kind !== 151 && + m.kind !== 153 && + m.kind !== 154) { + continue; + } + if (isCurrentlyEditingNode(m)) { + continue; + } + if (ts.hasModifier(m, 8)) { + continue; + } + var mIsStatic = ts.hasModifier(m, 32); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { @@ -61163,6 +62087,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(typeChecker, symbol, location); @@ -61198,6 +62125,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114: + case 113: + case 112: + case 117: + case 115: + case 123: + case 131: + case 125: + case 135: + case 120: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -61213,9 +62161,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -61227,8 +62175,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -61954,6 +62902,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62019,10 +62970,41 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -62044,7 +63026,7 @@ var ts; }); } function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -62072,25 +63054,20 @@ var ts; } } }); - if (sourceFile.flags & 65536) { - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 || decl.kind === 244) { - return decl; + switch (decl.kind) { + case 181: + case 238: + case 244: + return decl; + case 248: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248); - return decl.parent; } function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); @@ -62209,12 +63186,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); - ts.Debug.assert(!!name); - return name; } function skipExportSpecifierSymbol(symbol, checker) { if (symbol.declarations) @@ -62257,12 +63235,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; if (definition) { @@ -62272,39 +63251,41 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); if (node.parent.kind === 262) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -62314,10 +63295,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -62454,7 +63431,7 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265) { return undefined; @@ -62465,6 +63442,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { if (!options.implementations && node.kind === 9) { @@ -62472,12 +63450,59 @@ var ts; } return undefined; } - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9) { + return false; + } + switch (node.parent.kind) { + case 233: + case 248: + case 238: + case 244: + return true; + case 181: + return ts.isRequireCall(node.parent, false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265: + break; + case 233: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); @@ -62672,7 +63697,11 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; if (!symbolName || !symbolName.length) { return positions; @@ -62697,15 +63726,11 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -62714,27 +63739,27 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -62751,10 +63776,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -62862,7 +63885,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63092,9 +64115,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97) { continue; @@ -63138,13 +64161,13 @@ var ts; if (searchSpaceNode.kind === 265) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -63188,10 +64211,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -63199,8 +64222,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); @@ -63329,20 +64352,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -63481,12 +64504,10 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 71 && - (node.parent === declaration || - (declaration.kind === 242 && declaration.parent && declaration.parent.kind === 241))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } if (node.parent.kind === 262) { @@ -63500,21 +64521,11 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -63533,13 +64544,13 @@ var ts; return undefined; } if (type.flags & 65536 && !(type.flags & 16)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -63547,6 +64558,23 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239: + case 237: + return true; + case 242: + return declaration.parent.kind === 241; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -63611,7 +64639,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -63638,7 +64666,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -63707,6 +64735,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -63717,8 +64746,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -64092,8 +65119,8 @@ var ts; } }); }; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } rawItems = ts.filter(rawItems, function (item) { @@ -64134,16 +65161,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64167,8 +65197,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64201,6 +65232,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64209,8 +65241,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64424,8 +65456,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64503,9 +65535,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64522,7 +65554,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -65742,7 +66774,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 181 || node.parent.kind === 182) { + if (ts.isCallOrNewExpression(node.parent)) { var callExpression = node.parent; if (node.kind === 27 || node.kind === 19) { @@ -66120,7 +67152,7 @@ var ts; } } var callExpressionLike = void 0; - if (location.kind === 181 || location.kind === 182) { + if (ts.isCallOrNewExpression(location)) { callExpressionLike = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -66185,24 +67217,29 @@ var ts; } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { + return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 152) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; } } } @@ -66266,9 +67303,9 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 145); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; + var decl = ts.getDeclarationOfKind(symbol, 145); + ts.Debug.assert(decl !== undefined); + var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); @@ -66302,7 +67339,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } } } @@ -66548,7 +67585,7 @@ var ts; ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); ts.addRange(diagnostics, program.getOptionsDiagnostics()); } - program.emit(); + program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } @@ -66822,9 +67859,10 @@ var ts; var formatting; (function (formatting) { var FormattingContext = (function () { - function FormattingContext(sourceFile, formattingRequestKind) { + function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; + this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); @@ -67062,7 +68100,7 @@ var ts; this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); @@ -67070,10 +68108,10 @@ var ts; this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -67090,11 +68128,12 @@ var ts; this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); @@ -67102,8 +68141,8 @@ var ts; this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); @@ -67134,6 +68173,41 @@ var ts; this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -67177,7 +68251,25 @@ var ts; this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator + this.NoSpaceBeforeNonNullAssertionOperator, + this.NoSpaceAfterNewKeywordOnConstructorSignature + ]; + this.UserConfigurableRules = [ + this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, + this.SpaceAfterComma, this.NoSpaceAfterComma, + this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, + this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, + this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, + this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, + this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, + this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, + this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, + this.NewLineBeforeOpenBraceInControl, + this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, + this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion ]; this.LowPriorityCommonRules = [ this.NoSpaceBeforeSemicolon, @@ -67188,41 +68280,6 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; @@ -67233,6 +68290,18 @@ var ts; } throw new Error("Unknown rule"); }; + Rules.IsOptionEnabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + }; + Rules.IsOptionDisabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + }; + Rules.IsOptionDisabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + }; + Rules.IsOptionEnabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + }; Rules.IsForContext = function (context) { return context.contextNode.kind === 214; }; @@ -67448,6 +68517,9 @@ var ts; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 163; }; + Rules.IsConstructorSignatureContext = function (context) { + return context.contextNode.kind === 156; + }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 27 && token.kind !== 29) { return false; @@ -67529,8 +68601,7 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); @@ -67638,27 +68709,14 @@ var ts; (function (formatting) { var Shared; (function (Shared) { - var TokenRangeAccess = (function () { - function TokenRangeAccess(from, to, except) { - this.tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } - TokenRangeAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenRangeAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0; token <= 142; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -67666,9 +68724,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -67679,18 +68737,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0; token <= 142; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -67698,51 +68752,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92, 93, 142, 118, 126]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43, 44, 52, 51]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 71, 19, 21, 17, 99, 94]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([71, 133, 136, 122, 137, 105, 119]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); + TokenRange.Keywords = TokenRange.FromRange(72, 142); + TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92, 93, 142, 118, 126 + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43, 44, 52, 51 + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8, 71, 19, 21, + 17, 99, 94 + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71, 133, 136, 122, + 137, 105, 119 + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -67753,6 +68836,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -67768,121 +68853,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -68067,7 +69040,7 @@ var ts; return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -68150,7 +69123,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -68923,9 +69896,7 @@ var ts; if (node.kind === 20) { return -1; } - if (node.parent && (node.parent.kind === 181 || - node.parent.kind === 182) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -69421,7 +70392,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3, node, sourceFile, writer); @@ -69450,27 +70421,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); var newNode = ts.nodeIsSynthesized(visited) ? visited : (Proxy.prototype = visited, new Proxy()); @@ -69513,6 +70465,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -69579,14 +70541,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -69609,6 +70571,48 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69672,7 +70676,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -69750,7 +70755,7 @@ var ts; if (!isStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignatureDeclaration(undefined, undefined, [indexingParameter], typeNode); + var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ @@ -69764,6 +70769,56 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4) { + flags |= 1920; + } + if (meaning & 2) { + flags |= 793064; + } + if (meaning & 1) { + flags |= 107455; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69952,120 +71007,125 @@ var ts; } switch (token.kind) { case 71: - switch (token.parent.kind) { - case 226: - switch (token.parent.parent.parent.kind) { - case 214: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215: - return undefined; - case 260: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - case 145: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); - case 242: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); - } - else { - return deleteNodeInList(token.parent); - } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); - } - else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149: case 240: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226: + return deleteVariableDeclaration(token.parent); + case 145: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + case 237: + var importEquals = ts.getAncestor(token, 237); + return deleteNode(importEquals); + case 242: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = ts.getAncestor(token, 238); + return deleteNode(importSpec); + } + else { + return deleteNodeInList(token.parent); + } + case 239: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238); + return deleteNode(importDecl); + } + else { + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26) { + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215: + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -70096,6 +71156,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -70178,342 +71247,335 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, false, true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, false, true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238) { + return node; } - } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240) { + namespaceImportDeclaration = declaration; } - if (node.kind === 237) { - return node; + else { + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 || statement.kind === 238) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), undefined) + : isNamespaceImport + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -70628,7 +71690,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -70677,7 +71739,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -70718,7 +71780,7 @@ var ts; return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { @@ -70736,8 +71798,173 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + if (!(symbol.flags & 4)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + case 187: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + if (arrowFunctionBody.kind === 207) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + default: + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186) { + return undefined; + } + if (node.name.kind !== 71) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : @@ -71116,13 +72343,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -71465,7 +72693,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -71489,9 +72717,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -71718,7 +72943,7 @@ var ts; } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -71732,7 +72957,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -71765,11 +72990,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); @@ -72017,8 +73242,7 @@ var ts; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -72066,11 +73290,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -72184,20 +73432,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -72734,6 +73982,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -74423,7 +75674,7 @@ var ts; var oldProgram = this.program; this.program = this.languageService.getProgram(); var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { hasChanges = true; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -74680,6 +75931,11 @@ var ts; return; } var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.allowLocalPluginLoads) { + var local = ts.getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); + searchPaths.unshift(local); + } if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -75064,6 +76320,7 @@ var ts; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); @@ -76263,6 +77520,9 @@ var ts; CommandNames.GetCodeFixes = "getCodeFixes"; CommandNames.GetCodeFixesFull = "getCodeFixes-full"; CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; + CommandNames.GetApplicableRefactors = "getApplicableRefactors"; + CommandNames.GetRefactorCodeActions = "getRefactorCodeActions"; + CommandNames.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); @@ -76596,6 +77856,15 @@ var ts; _a[CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, + _a[CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[CommandNames.GetRefactorCodeActions] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, true)); + }, + _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -76626,7 +77895,8 @@ var ts; throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); @@ -77562,6 +78832,47 @@ var ts; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + var position = undefined; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return { position: position, textRange: textRange }; + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + }; + Session.prototype.getRefactorCodeActions = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + var result = project.getLanguageService().getRefactorCodeActions(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactorName); + if (simplifiedResult) { + return { + actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + }; + } + else { + return { + actions: result + }; + } + }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; if (args.errorCodes.length === 0) { @@ -77569,8 +78880,7 @@ var ts; } var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = getStartPosition(); - var endPosition = getEndPosition(); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); if (!codeActions) { @@ -77582,12 +78892,24 @@ var ts; else { return codeActions; } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition = undefined, endPosition = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; }; Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { var _this = this; @@ -78878,7 +80200,8 @@ var ts; logger: logger, canUseEvents: canUseEvents, globalPlugins: options.globalPlugins, - pluginProbeLocations: options.pluginProbeLocations + pluginProbeLocations: options.pluginProbeLocations, + allowLocalPluginLoads: options.allowLocalPluginLoads }) || this; if (telemetryEnabled && typingsInstaller) { typingsInstaller.setTelemetrySender(_this); @@ -79121,12 +80444,11 @@ var ts; sys.gc = function () { return global.gc(); }; } sys.require = function (initialDir, moduleName) { - var result = ts.nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, undefined, true); try { - return { module: require(result.resolvedModule.resolvedFileName), error: undefined }; + return { module: require(ts.resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; } - catch (e) { - return { module: undefined, error: e }; + catch (error) { + return { module: undefined, error: error }; } }; var cancellationToken; @@ -79152,6 +80474,7 @@ var ts; var typingSafeListLocation = server.findArgument("--typingSafeListLocation"); var globalPlugins = (server.findArgument("--globalPlugins") || "").split(","); var pluginProbeLocations = (server.findArgument("--pluginProbeLocations") || "").split(","); + var allowLocalPluginLoads = server.hasArgument("--allowLocalPluginLoads"); var useSingleInferredProject = server.hasArgument("--useSingleInferredProject"); var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition"); var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); @@ -79167,7 +80490,8 @@ var ts; telemetryEnabled: telemetryEnabled, logger: logger, globalPlugins: globalPlugins, - pluginProbeLocations: pluginProbeLocations + pluginProbeLocations: pluginProbeLocations, + allowLocalPluginLoads: allowLocalPluginLoads }; var ioSession = new IOSession(options); process.on("uncaughtException", function (err) { @@ -79177,3 +80501,5 @@ var ts; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); + +//# sourceMappingURL=tsserver.js.map diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 189883c63e6..643a9e80d06 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -352,9 +352,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -482,9 +483,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -495,7 +498,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -503,7 +506,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -516,7 +519,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -528,7 +531,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -537,7 +540,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -559,7 +562,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -581,7 +584,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -589,7 +592,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -926,7 +929,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -991,7 +994,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1051,6 +1054,10 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1172,7 +1179,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1185,11 +1192,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1213,7 +1220,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1266,13 +1273,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1298,13 +1305,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1435,7 +1442,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1626,11 +1633,11 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1640,37 +1647,47 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1831,18 +1848,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1854,15 +1871,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } const enum ObjectFlags { Class = 1, @@ -1896,7 +1915,7 @@ declare namespace ts { } interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -1932,7 +1951,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } const enum IndexKind { @@ -1961,9 +1980,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2204,6 +2223,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2362,13 +2382,13 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2384,7 +2404,7 @@ declare namespace ts { error?: Diagnostic; }; function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -2395,9 +2415,6 @@ declare namespace ts { }; } declare namespace ts { - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -2466,6 +2483,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; function createLoopVariable(): Identifier; function createUniqueName(text: string): Identifier; @@ -2480,58 +2498,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2539,6 +2518,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2580,7 +2598,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2600,16 +2618,15 @@ 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 createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2641,10 +2658,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2653,6 +2679,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2683,20 +2711,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2712,6 +2740,8 @@ declare namespace ts { function createNotEmittedStatement(original: Node): NotEmittedStatement; function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -2745,8 +2775,8 @@ declare namespace ts { function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; function addEmitHelper(node: T, helper: EmitHelper): T; function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; function removeEmitHelper(node: Node, helper: EmitHelper): boolean; @@ -2756,7 +2786,7 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; @@ -2789,6 +2819,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -2931,6 +2962,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -2981,6 +3014,10 @@ declare namespace ts { description: string; changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; caretOffset: number; @@ -3367,6 +3404,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; @@ -3610,6 +3648,9 @@ declare namespace ts.server.protocol { type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; type GetCodeFixes = "getCodeFixes"; type GetSupportedCodeFixes = "getSupportedCodeFixes"; + type GetApplicableRefactors = "getApplicableRefactors"; + type GetRefactorCodeActions = "getRefactorCodeActions"; + type GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; } interface Message { seq: number; @@ -3704,15 +3745,44 @@ declare namespace ts.server.protocol { line: number; offset: number; } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + interface ApplicableRefactorInfo { + name: string; + description: string; + } + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + interface GetRefactorCodeActionsRequest extends Request { + command: CommandTypes.GetRefactorCodeActions; + arguments: GetRefactorCodeActionsRequestArgs; + } + type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & { + refactorName: string; + }; + type RefactorCodeActions = { + actions: protocol.CodeAction[]; + renameLocation?: number; + }; + interface GetRefactorCodeActionsResponse extends Response { + body: RefactorCodeActions; + } interface CodeFixRequest extends Request { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } - interface CodeFixRequestArgs extends FileRequestArgs { + interface FileRangeRequestArgs extends FileRequestArgs { startLine: number; startOffset: number; endLine: number; endOffset: number; + } + interface CodeFixRequestArgs extends FileRangeRequestArgs { errorCodes?: number[]; } interface GetCodeFixesResponse extends Response { @@ -4291,6 +4361,7 @@ declare namespace ts.server.protocol { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; @@ -4408,7 +4479,7 @@ declare namespace ts.server { project: Project; } interface EventSender { - event(payload: any, eventName: string): void; + event(payload: T, eventName: string): void; } namespace CommandNames { const Brace: protocol.CommandTypes.Brace; @@ -4455,6 +4526,9 @@ declare namespace ts.server { const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects; const GetCodeFixes: protocol.CommandTypes.GetCodeFixes; const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes; + const GetApplicableRefactors: protocol.CommandTypes.GetApplicableRefactors; + const GetRefactorCodeActions: protocol.CommandTypes.GetRefactorCodeActions; + const GetRefactorCodeActionsFull: protocol.CommandTypes.GetRefactorCodeActionsFull; } function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; interface SessionOptions { @@ -4470,6 +4544,7 @@ declare namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } class Session implements EventSender { private readonly gcTimer; @@ -4491,7 +4566,7 @@ declare namespace ts.server { logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; - event(info: any, eventName: string): void; + event(info: T, eventName: string): void; output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private semanticCheck(file, project); private syntacticCheck(file, project); @@ -4554,7 +4629,12 @@ declare namespace ts.server { private getNavigationTree(args, simplifiedResult); private getNavigateToItems(args, simplifiedResult); private getSupportedCodeFixes(); + private isLocation(locationOrSpan); + private extractPositionAndRange(args, scriptInfo); + private getApplicableRefactors(args); + private getRefactorCodeActions(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); + private getStartAndEndPosition(args, scriptInfo); private mapCodeAction(codeAction, scriptInfo); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); @@ -5047,6 +5127,7 @@ declare namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } class ProjectService { readonly typingsCache: TypingsCache; @@ -5076,6 +5157,7 @@ declare namespace ts.server { private readonly eventHandler?; readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; + readonly allowLocalPluginLoads: boolean; constructor(opts: ProjectServiceOptions); ensureInferredProjectsUpToDate_TestOnly(): void; getCompilerOptionsForInferredProjects(): CompilerOptions; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 52c8a2207c4..e23edda9295 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -332,9 +332,10 @@ var ts; SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -469,6 +470,12 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -478,12 +485,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -604,6 +619,11 @@ var ts; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -671,21 +691,21 @@ var ts; TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; @@ -1011,6 +1031,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1025,14 +1046,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1288,6 +1312,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1492,6 +1525,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -2516,6 +2571,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3571,6 +3630,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -3678,7 +3738,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -3873,6 +3933,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4168,6 +4236,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4213,6 +4282,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4294,6 +4365,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -4842,9 +4916,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6855,49 +6930,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -6907,37 +6961,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -6968,9 +6992,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -6987,9 +7008,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -7245,12 +7323,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -7534,6 +7611,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -7667,12 +7746,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -7702,7 +7787,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -8087,9 +8171,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -8246,26 +8328,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -8472,10 +8556,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -8727,6 +8807,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -8951,6 +9040,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -9504,21 +9597,46 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -9618,21 +9736,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -9660,12 +9776,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -9710,7 +9827,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -9985,6 +10103,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -10088,12 +10208,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -10182,7 +10303,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -10234,7 +10355,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -10723,13 +10844,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -10977,10 +11098,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -11048,9 +11165,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -11248,6 +11376,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -11334,6 +11463,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -11356,6 +11489,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -11427,8 +11564,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -11544,6 +11681,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11882,15 +12061,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -11978,237 +12166,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -12219,42 +12182,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -12291,6 +12218,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -12312,7 +12259,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -12325,7 +12289,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -12335,7 +12299,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -12403,6 +12367,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -12448,9 +12655,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -12463,9 +12669,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -12513,9 +12718,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -12705,10 +12910,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -12835,6 +13040,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -12849,6 +13067,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -12858,7 +13080,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -12878,35 +13100,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -13125,6 +13318,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -13173,6 +13399,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -13193,7 +13461,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -13234,6 +13502,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -13264,7 +13544,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -13450,19 +13731,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -13477,6 +13745,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -13502,20 +13782,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -13524,10 +13790,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -13537,12 +13803,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -13551,10 +13829,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -13566,10 +13844,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -13580,10 +13858,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -13593,10 +13871,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -13691,14 +13968,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -13719,6 +13996,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -14029,6 +14329,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -14269,7 +14588,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -14376,9 +14697,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -14489,16 +14811,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -14667,6 +14979,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -14819,7 +15159,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15476,6 +15816,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -19818,6 +20160,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -20578,7 +20922,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -20606,7 +20950,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -20639,19 +20983,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -20747,9 +21092,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -22399,7 +22744,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -22414,7 +22759,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -22429,7 +22774,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -22442,7 +22787,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -23177,6 +23522,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -23321,13 +23667,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -23400,11 +23749,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -23661,16 +24012,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -23743,9 +24094,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -23753,7 +24101,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -23781,7 +24129,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -23856,7 +24205,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -23865,7 +24218,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -23912,12 +24265,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -23926,7 +24279,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -23935,7 +24288,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -23957,7 +24310,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -24004,7 +24357,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -24014,7 +24367,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -24111,6 +24474,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -24142,13 +24509,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -24160,7 +24527,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -24263,10 +24630,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -24282,7 +24649,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -24404,7 +24771,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -24424,6 +24791,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -24483,7 +24855,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -24624,7 +24995,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -24894,34 +25265,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -24931,12 +25327,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -24953,23 +25349,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -24989,8 +25387,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -25001,72 +25399,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -25074,12 +25453,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -25121,41 +25500,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -25163,7 +25553,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -25173,48 +25563,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -25223,74 +25637,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -25298,18 +25759,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -25318,20 +25779,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -25357,28 +25808,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -25396,12 +25848,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -25437,13 +25891,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -25486,7 +25941,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -25551,12 +26006,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -25893,7 +26351,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -26144,10 +26602,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -26268,7 +26723,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -26368,7 +26823,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -26446,6 +26901,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -26462,16 +26918,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -26681,7 +27144,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -26737,7 +27200,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -26913,11 +27376,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -27081,77 +27545,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -27383,7 +27850,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -27460,8 +27927,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -27605,7 +28072,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -27725,6 +28192,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -27781,8 +28269,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -27824,7 +28312,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -27838,12 +28326,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -27909,7 +28397,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -28272,8 +28760,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -28400,8 +28889,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -28431,7 +28920,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -28443,7 +28932,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -28463,7 +28952,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -28475,7 +28964,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -28512,14 +29000,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -28578,16 +29067,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -28809,14 +29298,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -28824,8 +29313,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -28946,8 +29435,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -28998,9 +29487,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -29030,12 +29519,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -29050,11 +29539,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -29079,7 +29568,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -29211,7 +29700,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -29228,11 +29717,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -29259,15 +29748,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -29278,11 +29768,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -29537,7 +30029,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -29948,29 +30440,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -29981,42 +30471,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -30200,24 +30695,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -30566,10 +31043,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -30666,23 +31143,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -30793,7 +31281,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -30816,11 +31304,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -30859,8 +31347,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -30938,8 +31426,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -30947,8 +31435,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -30971,7 +31459,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -31011,27 +31499,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -31039,43 +31527,43 @@ 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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -31220,7 +31708,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -31297,7 +31785,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -31330,20 +31818,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -31356,7 +31834,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -31444,26 +31922,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -31546,8 +32023,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31622,7 +32099,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -31632,7 +32109,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -31697,7 +32174,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -31757,8 +32234,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -31774,15 +32251,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -31984,7 +32462,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -32007,8 +32485,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -32077,8 +32555,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -32104,7 +32582,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -32130,7 +32608,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -32250,7 +32728,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -32683,6 +33161,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -32737,7 +33231,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -32767,12 +33261,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -33467,8 +33961,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -33559,7 +34053,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -33574,7 +34068,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -33712,6 +34206,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -33771,6 +34267,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -33788,6 +34288,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -33797,37 +34300,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -33837,9 +34340,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -33849,11 +34351,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -33908,7 +34414,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -33942,6 +34459,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -33951,6 +34482,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -33976,6 +34508,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -34021,7 +34554,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -34179,6 +34712,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -34190,7 +34741,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -34208,36 +34768,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -34312,42 +34854,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -34383,7 +34889,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -34399,6 +34905,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -34506,7 +35113,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -34529,8 +35142,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -34617,7 +35230,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -34853,7 +35466,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -34931,7 +35544,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -34959,7 +35572,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -35000,25 +35613,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -35028,14 +35672,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -35166,7 +35802,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -35293,8 +35929,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -35438,7 +36074,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -35502,10 +36138,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -35789,15 +36425,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -35877,7 +36513,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -35920,8 +36556,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -35935,8 +36571,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -35945,8 +36581,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -35981,7 +36617,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -36253,7 +36889,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -36307,7 +36943,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -36389,12 +37025,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -36434,9 +37070,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -36490,7 +37126,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -36787,17 +37423,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -36820,7 +37453,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -36941,7 +37574,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -37015,7 +37648,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -37153,7 +37787,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -37192,7 +37826,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -37242,16 +37876,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -37262,7 +37896,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -37370,7 +38004,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -37383,8 +38017,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -37433,11 +38067,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -37633,7 +38268,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -37643,6 +38280,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -37669,7 +38343,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -37678,15 +38352,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -37799,15 +38473,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -37885,7 +38560,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -37947,7 +38622,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -37961,7 +38636,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -38157,7 +38832,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -38263,11 +38938,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -38717,11 +39393,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -38936,7 +39615,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -38955,7 +39634,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -38970,13 +39649,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -38995,7 +39671,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -39078,88 +39754,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -39172,75 +39841,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -39263,7 +39910,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -39488,6 +40135,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -40134,7 +40784,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -40247,7 +40897,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -40309,16 +40959,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -40579,7 +41229,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -40607,7 +41257,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -40619,15 +41269,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -40706,7 +41347,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -40853,7 +41493,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -40880,9 +41520,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -41911,6 +42552,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -42021,49 +42673,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -42074,20 +42736,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -42124,12 +42772,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -42146,6 +42794,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -42190,6 +42840,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -42198,6 +42852,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -42222,8 +42878,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -42232,6 +42886,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -42256,6 +42912,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -42311,6 +42969,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -42649,6 +43314,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -43099,7 +43767,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -43888,15 +44556,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -44183,7 +44846,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -44230,9 +44898,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -44365,7 +45033,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -44675,7 +45343,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -44920,7 +45588,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -44988,19 +45656,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -45127,6 +45790,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -45134,19 +45800,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -45155,12 +45819,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -45392,12 +46051,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -45409,11 +46078,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -45432,7 +46101,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -45870,7 +46539,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -46012,7 +46681,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -46875,12 +47544,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -47768,7 +48438,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -47936,8 +48606,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -49623,7 +50292,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -49786,9 +50455,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -50292,9 +50961,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -50807,9 +51474,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -51100,7 +51767,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -51215,7 +51882,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -51273,7 +51940,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -51443,7 +52110,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -51468,11 +52135,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -51876,8 +52543,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -51890,23 +52556,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -51916,12 +52589,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -51991,7 +52658,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -52219,7 +52886,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -52316,7 +52983,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -52328,12 +52995,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -52347,7 +53008,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -52362,6 +53023,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -52369,15 +53043,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -52398,7 +53079,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -52450,7 +53131,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -52458,7 +53140,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -52653,6 +53335,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -52911,7 +53598,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -53674,7 +54361,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -53705,7 +54392,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -53791,7 +54478,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -53867,7 +54556,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -54067,7 +54756,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -54087,7 +54776,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -54149,6 +54838,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -54174,6 +54865,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -54196,6 +54888,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -54310,7 +55003,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -54348,9 +55043,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -54361,8 +55062,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -54375,7 +55081,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -54451,7 +55157,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -54542,7 +55248,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -55221,6 +55927,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -55469,6 +56178,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -55646,7 +56364,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -55860,14 +56580,17 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -56081,6 +56804,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -56130,6 +56930,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -56172,7 +56973,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -56221,7 +57023,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -56254,45 +57057,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -56301,15 +57123,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -56328,67 +57147,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -56396,11 +57221,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -56412,8 +57242,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -56753,7 +57582,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -56784,7 +57613,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -56825,13 +57653,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -56854,45 +57682,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -57028,10 +57861,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -57080,7 +57913,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -57177,12 +58010,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -57509,7 +58342,6 @@ var ts; case 148: case 261: case 262: - case 264: case 151: case 150: case 152: @@ -57526,9 +58358,11 @@ var ts; case 231: case 163: return 2; + case 264: case 229: - case 232: return 1 | 2; + case 232: + return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -57545,7 +58379,7 @@ var ts; case 238: case 243: case 244: - return 1 | 2 | 4; + return 7; case 265: return 4 | 1; } @@ -57700,7 +58534,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -57715,31 +58549,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -58045,43 +58854,24 @@ var ts; if (ts.isToken(current)) { return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -58175,10 +58965,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; function isInsideJsxElementOrAttribute(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); if (!token) { @@ -58207,20 +58993,29 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end); }); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { + return kind === 2 || + !(text.charCodeAt(end - 1) === 47 && text.charCodeAt(end - 2) === 42); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); @@ -58336,6 +59131,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -58376,25 +59174,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119: @@ -58654,8 +59454,8 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; @@ -59202,7 +60002,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -59210,8 +60010,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60070,8 +60870,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -60328,7 +61128,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; } @@ -60352,13 +61152,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -60403,8 +61206,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -60461,10 +61264,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -60492,9 +61296,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -60502,16 +61307,20 @@ var ts; if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -60562,7 +61371,7 @@ var ts; var currentToken = ts.getTokenAtPosition(sourceFile, position); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -60592,7 +61401,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -60663,6 +61472,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -60693,7 +61503,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; @@ -60735,6 +61545,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -60742,6 +61553,10 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { @@ -60871,12 +61686,14 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174) { @@ -60893,7 +61710,10 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -60904,10 +61724,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -60933,6 +61749,42 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + isMemberCompletion = true; + isNewIdentifierLocation = true; + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32; + break; + } + } + if (!(classElementModifierFlags & 8)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -60961,6 +61813,37 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + case 26: + case 25: + case 18: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61050,7 +61933,7 @@ var ts; containingNodeKind === 231 || isFunction(containingNodeKind); case 115: - return containingNodeKind === 149; + return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: return containingNodeKind === 146 || (contextToken.parent && contextToken.parent.parent && @@ -61063,13 +61946,16 @@ var ts; return containingNodeKind === 242 || containingNodeKind === 246 || containingNodeKind === 240; + case 125: + case 135: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } case 75: case 83: case 109: case 89: case 104: - case 125: - case 135: case 91: case 110: case 76: @@ -61077,6 +61963,10 @@ var ts; case 138: return true; } + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61108,7 +61998,7 @@ var ts; var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -61134,7 +62024,7 @@ var ts; m.kind !== 154) { continue; } - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -61144,17 +62034,51 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + if (m.kind !== 149 && + m.kind !== 151 && + m.kind !== 153 && + m.kind !== 154) { + continue; + } + if (isCurrentlyEditingNode(m)) { + continue; + } + if (ts.hasModifier(m, 8)) { + continue; + } + var mIsStatic = ts.hasModifier(m, 32); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { @@ -61163,6 +62087,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(typeChecker, symbol, location); @@ -61198,6 +62125,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114: + case 113: + case 112: + case 117: + case 115: + case 123: + case 131: + case 125: + case 135: + case 120: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -61213,9 +62161,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -61227,8 +62175,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -61954,6 +62902,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62019,10 +62970,41 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -62044,7 +63026,7 @@ var ts; }); } function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -62072,25 +63054,20 @@ var ts; } } }); - if (sourceFile.flags & 65536) { - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 || decl.kind === 244) { - return decl; + switch (decl.kind) { + case 181: + case 238: + case 244: + return decl; + case 248: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248); - return decl.parent; } function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); @@ -62209,12 +63186,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); - ts.Debug.assert(!!name); - return name; } function skipExportSpecifierSymbol(symbol, checker) { if (symbol.declarations) @@ -62257,12 +63235,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; if (definition) { @@ -62272,39 +63251,41 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); if (node.parent.kind === 262) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -62314,10 +63295,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -62454,7 +63431,7 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265) { return undefined; @@ -62465,6 +63442,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { if (!options.implementations && node.kind === 9) { @@ -62472,12 +63450,59 @@ var ts; } return undefined; } - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9) { + return false; + } + switch (node.parent.kind) { + case 233: + case 248: + case 238: + case 244: + return true; + case 181: + return ts.isRequireCall(node.parent, false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265: + break; + case 233: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); @@ -62672,7 +63697,11 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; if (!symbolName || !symbolName.length) { return positions; @@ -62697,15 +63726,11 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -62714,27 +63739,27 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -62751,10 +63776,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -62862,7 +63885,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63092,9 +64115,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97) { continue; @@ -63138,13 +64161,13 @@ var ts; if (searchSpaceNode.kind === 265) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -63188,10 +64211,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -63199,8 +64222,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); @@ -63329,20 +64352,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -63481,12 +64504,10 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 71 && - (node.parent === declaration || - (declaration.kind === 242 && declaration.parent && declaration.parent.kind === 241))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } if (node.parent.kind === 262) { @@ -63500,21 +64521,11 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -63533,13 +64544,13 @@ var ts; return undefined; } if (type.flags & 65536 && !(type.flags & 16)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -63547,6 +64558,23 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239: + case 237: + return true; + case 242: + return declaration.parent.kind === 241; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -63611,7 +64639,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -63638,7 +64666,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -63707,6 +64735,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -63717,8 +64746,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -64092,8 +65119,8 @@ var ts; } }); }; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } rawItems = ts.filter(rawItems, function (item) { @@ -64134,16 +65161,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64167,8 +65197,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64201,6 +65232,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64209,8 +65241,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64424,8 +65456,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64503,9 +65535,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64522,7 +65554,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -65742,7 +66774,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 181 || node.parent.kind === 182) { + if (ts.isCallOrNewExpression(node.parent)) { var callExpression = node.parent; if (node.kind === 27 || node.kind === 19) { @@ -66120,7 +67152,7 @@ var ts; } } var callExpressionLike = void 0; - if (location.kind === 181 || location.kind === 182) { + if (ts.isCallOrNewExpression(location)) { callExpressionLike = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -66185,24 +67217,29 @@ var ts; } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { + return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 152) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; } } } @@ -66266,9 +67303,9 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 145); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; + var decl = ts.getDeclarationOfKind(symbol, 145); + ts.Debug.assert(decl !== undefined); + var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); @@ -66302,7 +67339,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } } } @@ -66548,7 +67585,7 @@ var ts; ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); ts.addRange(diagnostics, program.getOptionsDiagnostics()); } - program.emit(); + program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } @@ -66822,9 +67859,10 @@ var ts; var formatting; (function (formatting) { var FormattingContext = (function () { - function FormattingContext(sourceFile, formattingRequestKind) { + function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; + this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); @@ -67062,7 +68100,7 @@ var ts; this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); @@ -67070,10 +68108,10 @@ var ts; this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -67090,11 +68128,12 @@ var ts; this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); @@ -67102,8 +68141,8 @@ var ts; this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); @@ -67134,6 +68173,41 @@ var ts; this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -67177,7 +68251,25 @@ var ts; this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator + this.NoSpaceBeforeNonNullAssertionOperator, + this.NoSpaceAfterNewKeywordOnConstructorSignature + ]; + this.UserConfigurableRules = [ + this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, + this.SpaceAfterComma, this.NoSpaceAfterComma, + this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, + this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, + this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, + this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, + this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, + this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, + this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, + this.NewLineBeforeOpenBraceInControl, + this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, + this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion ]; this.LowPriorityCommonRules = [ this.NoSpaceBeforeSemicolon, @@ -67188,41 +68280,6 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; @@ -67233,6 +68290,18 @@ var ts; } throw new Error("Unknown rule"); }; + Rules.IsOptionEnabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + }; + Rules.IsOptionDisabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + }; + Rules.IsOptionDisabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + }; + Rules.IsOptionEnabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + }; Rules.IsForContext = function (context) { return context.contextNode.kind === 214; }; @@ -67448,6 +68517,9 @@ var ts; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 163; }; + Rules.IsConstructorSignatureContext = function (context) { + return context.contextNode.kind === 156; + }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 27 && token.kind !== 29) { return false; @@ -67529,8 +68601,7 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); @@ -67638,27 +68709,14 @@ var ts; (function (formatting) { var Shared; (function (Shared) { - var TokenRangeAccess = (function () { - function TokenRangeAccess(from, to, except) { - this.tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } - TokenRangeAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenRangeAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0; token <= 142; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -67666,9 +68724,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -67679,18 +68737,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0; token <= 142; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -67698,51 +68752,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92, 93, 142, 118, 126]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43, 44, 52, 51]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 71, 19, 21, 17, 99, 94]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([71, 133, 136, 122, 137, 105, 119]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); + TokenRange.Keywords = TokenRange.FromRange(72, 142); + TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92, 93, 142, 118, 126 + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43, 44, 52, 51 + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8, 71, 19, 21, + 17, 99, 94 + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71, 133, 136, 122, + 137, 105, 119 + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -67753,6 +68836,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -67768,121 +68853,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -68067,7 +69040,7 @@ var ts; return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -68150,7 +69123,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -68923,9 +69896,7 @@ var ts; if (node.kind === 20) { return -1; } - if (node.parent && (node.parent.kind === 181 || - node.parent.kind === 182) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -69421,7 +70392,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3, node, sourceFile, writer); @@ -69450,27 +70421,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); var newNode = ts.nodeIsSynthesized(visited) ? visited : (Proxy.prototype = visited, new Proxy()); @@ -69513,6 +70465,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -69579,14 +70541,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -69609,6 +70571,48 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69672,7 +70676,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -69750,7 +70755,7 @@ var ts; if (!isStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignatureDeclaration(undefined, undefined, [indexingParameter], typeNode); + var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ @@ -69764,6 +70769,56 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4) { + flags |= 1920; + } + if (meaning & 2) { + flags |= 793064; + } + if (meaning & 1) { + flags |= 107455; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69952,120 +71007,125 @@ var ts; } switch (token.kind) { case 71: - switch (token.parent.kind) { - case 226: - switch (token.parent.parent.parent.kind) { - case 214: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215: - return undefined; - case 260: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - case 145: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); - case 242: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); - } - else { - return deleteNodeInList(token.parent); - } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); - } - else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149: case 240: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226: + return deleteVariableDeclaration(token.parent); + case 145: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + case 237: + var importEquals = ts.getAncestor(token, 237); + return deleteNode(importEquals); + case 242: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = ts.getAncestor(token, 238); + return deleteNode(importSpec); + } + else { + return deleteNodeInList(token.parent); + } + case 239: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238); + return deleteNode(importDecl); + } + else { + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26) { + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215: + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -70096,6 +71156,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -70178,342 +71247,335 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, false, true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, false, true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238) { + return node; } - } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240) { + namespaceImportDeclaration = declaration; } - if (node.kind === 237) { - return node; + else { + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 || statement.kind === 238) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), undefined) + : isNamespaceImport + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -70628,7 +71690,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -70677,7 +71739,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -70718,7 +71780,7 @@ var ts; return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { @@ -70736,8 +71798,173 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + if (!(symbol.flags & 4)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + case 187: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + if (arrowFunctionBody.kind === 207) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + default: + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186) { + return undefined; + } + if (node.name.kind !== 71) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : @@ -71116,13 +72343,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -71465,7 +72693,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -71489,9 +72717,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -71718,7 +72943,7 @@ var ts; } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -71732,7 +72957,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -71765,11 +72990,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); @@ -72017,8 +73242,7 @@ var ts; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -72066,11 +73290,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -72184,20 +73432,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -72582,6 +73830,9 @@ var ts; CommandNames.GetCodeFixes = "getCodeFixes"; CommandNames.GetCodeFixesFull = "getCodeFixes-full"; CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; + CommandNames.GetApplicableRefactors = "getApplicableRefactors"; + CommandNames.GetRefactorCodeActions = "getRefactorCodeActions"; + CommandNames.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); @@ -72915,6 +74166,15 @@ var ts; _a[CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, + _a[CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[CommandNames.GetRefactorCodeActions] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, true)); + }, + _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -72945,7 +74205,8 @@ var ts; throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); @@ -73881,6 +75142,47 @@ var ts; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + var position = undefined; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return { position: position, textRange: textRange }; + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + }; + Session.prototype.getRefactorCodeActions = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + var result = project.getLanguageService().getRefactorCodeActions(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactorName); + if (simplifiedResult) { + return { + actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + }; + } + else { + return { + actions: result + }; + } + }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; if (args.errorCodes.length === 0) { @@ -73888,8 +75190,7 @@ var ts; } var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = getStartPosition(); - var endPosition = getEndPosition(); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); if (!codeActions) { @@ -73901,12 +75202,24 @@ var ts; else { return codeActions; } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition = undefined, endPosition = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; }; Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { var _this = this; @@ -76213,7 +77526,7 @@ var ts; var oldProgram = this.program; this.program = this.languageService.getProgram(); var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { hasChanges = true; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -76470,6 +77783,11 @@ var ts; return; } var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.allowLocalPluginLoads) { + var local = ts.getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); + searchPaths.unshift(local); + } if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -76854,6 +78172,7 @@ var ts; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); @@ -78429,6 +79748,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -78591,3 +79913,5 @@ var TypeScript; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); var toolsVersion = "2.4"; + +//# sourceMappingURL=tsserverlibrary.js.map diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 2f11d458e20..5853aafb946 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -359,9 +359,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -474,6 +475,10 @@ declare namespace ts { type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ text: string; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; @@ -491,9 +496,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +511,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +519,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +532,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +544,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +553,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +575,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +597,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +605,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +957,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1016,7 +1023,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1076,6 +1083,13 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1197,7 +1211,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1224,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1252,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1311,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1344,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1481,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1706,11 +1720,11 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1720,38 +1734,48 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1912,18 +1936,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1935,15 +1959,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } enum ObjectFlags { Class = 1, @@ -1988,7 +2014,7 @@ declare namespace ts { */ interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -2024,7 +2050,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { @@ -2059,9 +2085,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2329,6 +2355,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2611,14 +2638,14 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2709,6 +2736,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -2727,58 +2755,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2786,6 +2775,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2827,7 +2855,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2847,16 +2875,15 @@ 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 createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2888,10 +2915,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2900,6 +2936,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2930,20 +2968,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2976,6 +3014,8 @@ declare namespace ts { */ function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -3040,11 +3080,11 @@ declare namespace ts { /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; /** * Sets the constant value to emit for an expression. */ - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; /** * Adds an EmitHelper to a node. */ @@ -3069,17 +3109,13 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** Array that is only intended to be pushed to, never read. */ - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -3218,6 +3254,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -3246,9 +3283,10 @@ declare namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3422,6 +3460,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3492,6 +3532,10 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -4006,6 +4050,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; diff --git a/lib/typescript.js b/lib/typescript.js index 4fe0eb9bf25..a73895f4f74 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -365,10 +365,11 @@ var ts; // Transformation nodes SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -512,6 +513,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); /** Return code used by getEmitOutput function to indicate status of the function */ var ExitStatus; (function (ExitStatus) { @@ -527,12 +535,23 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -677,6 +696,12 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -751,7 +776,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -761,7 +786,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; @@ -770,7 +795,7 @@ var ts; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; @@ -1119,6 +1144,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1138,17 +1164,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1450,12 +1481,6 @@ var ts; return undefined; } ts.forEach = forEach; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1477,6 +1502,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1704,6 +1738,35 @@ var ts; return result; } ts.flatMap = flatMap; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2881,6 +2944,11 @@ var ts; } ts.startsWith = startsWith; /* @internal */ + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -4058,6 +4126,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -4165,7 +4234,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -4360,6 +4429,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4655,6 +4732,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4700,6 +4778,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4781,6 +4861,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -5443,9 +5526,10 @@ var ts; ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6654,9 +6738,7 @@ var ts; ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -6849,28 +6931,30 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8 /* NumericLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -7099,10 +7183,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 /* EnumDeclaration */ && isConst(node); } @@ -7382,6 +7462,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151 /* MethodDeclaration */: @@ -7638,6 +7727,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183 /* TaggedTemplateExpression */) { return node.tag; @@ -8230,21 +8323,46 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 71 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { - return false; + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 /* ImportSpecifier */ || parent.kind === 246 /* ExportSpecifier */) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0 /* None */: + case 2 /* ModuleExports */: + return undefined; + case 1 /* ExportsProperty */: + if (lhs.kind === 71 /* Identifier */) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4 /* ThisProperty */: + case 5 /* Property */: + return lhs.name; + case 3 /* PrototypeProperty */: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && @@ -8357,21 +8475,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -8399,12 +8515,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8457,7 +8574,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -8740,6 +8858,8 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; + case 297 /* CommaListExpression */: + return 0; default: return -1; } @@ -8853,14 +8973,15 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -8949,7 +9070,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -9015,7 +9136,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; /** @@ -9579,13 +9700,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0 /* CarriageReturnLineFeed */) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; } - else if (options.newLine === 1 /* LineFeed */) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -9913,10 +10034,6 @@ var ts; return node.kind === 71 /* Identifier */; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; @@ -9989,9 +10106,20 @@ var ts; || kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */ || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */; + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 /* ConstructSignature */ + || kind === 155 /* CallSignature */ + || kind === 148 /* PropertySignature */ + || kind === 150 /* MethodSignature */ + || kind === 157 /* IndexSignature */ + || kind === 247 /* MissingDeclaration */; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 /* PropertyAssignment */ @@ -10209,6 +10337,7 @@ var ts; || kind === 198 /* SpreadElement */ || kind === 202 /* AsExpression */ || kind === 200 /* OmittedExpression */ + || kind === 297 /* CommaListExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -10297,6 +10426,10 @@ var ts; return node.kind === 237 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239 /* ImportClause */; } @@ -10319,6 +10452,10 @@ var ts; return node.kind === 246 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; } @@ -10390,8 +10527,8 @@ var ts; || kind === 213 /* WhileStatement */ || kind === 220 /* WithStatement */ || kind === 295 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + || kind === 299 /* EndOfDeclarationMarker */ + || kind === 298 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -10517,6 +10654,49 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10983,16 +11163,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - // Identifiers - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable) { @@ -11087,240 +11275,13 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - // Type Elements - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - // Types - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173 /* LiteralType */); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159 /* TypeReference */); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158 /* TypePredicate */); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162 /* TypeQuery */); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164 /* ArrayType */); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163 /* TypeLiteral */); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165 /* TupleType */); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172 /* MappedType */); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170 /* TypeOperator */); - typeOperatorNode.operator = 127 /* KeyOfKeyword */; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171 /* IndexedAccessType */); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; - // Type Declarations + // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145 /* TypeParameter */); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -11331,44 +11292,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - // Signature elements - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148 /* PropertySignature */); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157 /* IndexSignature */); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; - // Signature elements function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146 /* Parameter */); node.decorators = asNodeArray(decorators); @@ -11405,7 +11328,27 @@ var ts; : node; } ts.updateDecorator = updateDecorator; - // Type members + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); @@ -11427,7 +11370,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -11440,7 +11400,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -11450,7 +11410,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11518,6 +11478,251 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164 /* ArrayType */); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170 /* TypeOperator */); + node.operator = 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174 /* ObjectBindingPattern */); @@ -11565,9 +11770,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11580,9 +11784,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11632,9 +11835,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11824,10 +12027,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11954,6 +12157,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205 /* TemplateSpan */); @@ -11969,6 +12185,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { var block = createSynthesizedNode(207 /* Block */); @@ -11979,7 +12199,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11999,35 +12219,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209 /* EmptyStatement */); } @@ -12246,6 +12437,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); @@ -12294,6 +12518,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); @@ -12314,7 +12580,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233 /* ModuleDeclaration */); - node.flags |= flags; + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -12355,6 +12621,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); @@ -12385,7 +12663,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12573,19 +12852,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254 /* JsxAttributes */); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253 /* JsxAttribute */); node.name = name; @@ -12600,6 +12866,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); node.expression = expression; @@ -12626,20 +12904,6 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; // Clauses - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12648,10 +12912,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12661,12 +12925,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260 /* CatchClause */); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12675,10 +12951,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; // Property assignments @@ -12691,10 +12967,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12705,10 +12981,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12718,10 +12994,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; // Enum @@ -12833,7 +13108,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12845,7 +13120,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12874,6 +13149,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266 /* Bundle */); node.sourceFiles = sourceFiles; @@ -13250,7 +13548,25 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // Compound nodes + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -13512,7 +13828,11 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13686,9 +14006,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13846,16 +14167,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -14131,6 +14442,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; /** * Clones a series of not-emitted expressions with a new inner expression. * @@ -14311,7 +14650,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15079,6 +15418,8 @@ var ts; return visitNode(cbNode, node.expression); case 247 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 297 /* CommaListExpression */: + return visitNodes(cbNodes, node.elements); case 249 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -20465,6 +20806,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -21452,7 +21795,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -21480,7 +21823,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -21517,12 +21860,13 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21530,7 +21874,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21674,9 +22018,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -23592,7 +23936,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -23611,7 +23955,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23626,7 +23970,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23639,7 +23983,7 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -24526,13 +24870,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -24860,6 +25202,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25062,13 +25406,24 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -25099,7 +25454,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -25462,6 +25816,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -25613,13 +25968,16 @@ var ts; // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -25702,11 +26060,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -25972,16 +26332,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26063,9 +26423,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -26073,7 +26430,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -26109,7 +26466,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26205,7 +26563,11 @@ var ts; // 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 // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; var propertyWithInvalidInitializer; @@ -26215,7 +26577,7 @@ var ts; loop: while (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 = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { // symbol lookup restrictions for function-like declarations @@ -26286,12 +26648,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { break loop; } break; case 232 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; @@ -26306,7 +26668,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -26316,7 +26678,7 @@ var ts; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -26351,7 +26713,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -26412,7 +26774,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -26422,7 +26784,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -26541,6 +26913,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -26573,13 +26949,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -26595,7 +26971,7 @@ var ts; if (node.kind === 237 /* ImportEqualsDeclaration */) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238 /* ImportDeclaration */; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -26719,10 +27095,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); @@ -26738,7 +27114,7 @@ var ts; case 242 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 243 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236 /* NamespaceExportDeclaration */: @@ -26887,7 +27263,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26909,6 +27285,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; @@ -26978,7 +27359,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -27128,7 +27508,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32 /* StringLiteral */, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started @@ -27458,34 +27838,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -27495,15 +27900,14 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } if (type.flags & 1 /* Any */) { @@ -27518,23 +27922,25 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 16 /* Enum */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + } + if (type.flags & 272 /* EnumLike */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256 /* EnumLiteral */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & 1024 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } @@ -27554,8 +27960,8 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -27566,39 +27972,31 @@ var ts; ts.Debug.assert(!!(type.flags & 32768 /* Object */)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3 /* ClassOrInterface */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - // TODO(aozgaa): handle type arguments. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & 16384 /* TypeParameter */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536 /* Union */) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166 /* UnionType */, unionTypeNodes); + if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { + var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072 /* Intersection */) { - return ts.createUnionOrIntersectionTypeNode(167 /* IntersectionType */, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); // The type is an object literal type. @@ -27606,35 +28004,23 @@ var ts; } if (type.flags & 262144 /* Index */) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -27643,14 +28029,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); } else if (ts.contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27696,41 +28082,53 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(/*members*/ undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -27738,7 +28136,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27751,48 +28149,72 @@ var ts; // 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)) { - var qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, /*right*/ undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71 /* Identifier */) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71 /* Identifier */) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); } var properties = resolvedType.properties; if (!properties) { @@ -27801,86 +28223,131 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 136 /* StringKeyword */ : 133 /* NumberKeyword */); - var name = ts.getNameFromIndexInfo(indexInfo); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration( + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - // TODO(aozgaa): In the future, check initializer accessibility. - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24 /* DotDotDotToken */), - // Clone name to remove trivia. - ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55 /* QuestionToken */), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048 /* Undefined */); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0 /* None */, /*endOfChain*/ true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -27888,19 +28355,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -27909,20 +28375,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -27954,28 +28410,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -27993,12 +28450,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -28034,13 +28493,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28097,7 +28557,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -28180,12 +28640,17 @@ var ts; else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -28541,7 +29006,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -28808,10 +29273,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246 /* ExportSpecifier */) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -28954,7 +29416,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -29070,7 +29532,7 @@ var ts; return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -29173,6 +29635,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : @@ -29189,17 +29652,25 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536 /* JavaScriptFile */) { - // If there is a JSDoc type, use it - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding @@ -29449,7 +29920,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; } } } @@ -29512,7 +29983,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -29711,6 +30182,7 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && @@ -29718,7 +30190,7 @@ var ts; // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; @@ -29902,77 +30374,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 /* NumericLiteral */ || + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 71 /* Identifier */ && !!symbol.exports.get(expr.text); + expr.kind === 71 /* Identifier */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256 /* EnumLiteral */); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536 /* Union */; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 65536 /* Union */) { + enumType_1.flags |= 256 /* EnumLiteral */; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -30219,7 +30694,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -30306,8 +30781,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -30481,7 +30956,7 @@ var ts; // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); @@ -30613,6 +31088,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190 /* Primitive */) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : @@ -30674,8 +31170,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -30731,7 +31227,7 @@ var ts; var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : @@ -30746,12 +31242,12 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -30823,7 +31319,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -31231,8 +31727,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -31367,8 +31864,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_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -31399,7 +31896,7 @@ var ts; return ts.length(type.target.typeParameters); } // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -31414,7 +31911,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -31437,7 +31934,7 @@ var ts; // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -31449,7 +31946,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -31489,14 +31985,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 /* Value */ && node.kind === 277 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In @@ -31559,10 +32056,7 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. @@ -31571,6 +32065,9 @@ var ts; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -31812,14 +32309,14 @@ 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, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31827,8 +32324,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -31959,8 +32456,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 addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -32024,9 +32521,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -32056,12 +32553,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? - indexType.text : + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -32076,11 +32573,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { @@ -32105,7 +32602,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -32258,7 +32755,7 @@ var ts; var rightProp = _a[_i]; // we approximate own properties as non-methods plus methods that are inside the object literal var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -32275,11 +32772,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { + if (rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -32306,15 +32803,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32325,11 +32823,17 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -32593,7 +33097,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { var links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases @@ -33087,29 +33591,27 @@ var ts; type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8 /* EnumMember */) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33120,42 +33622,50 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + if (t & 1 /* Any */ || s & 8192 /* Never */) return true; - if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) + if (s & 262178 /* StringLike */ && t & 2 /* String */) return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + if (s & 84 /* NumberLike */ && t & 4 /* Number */) return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { + if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 /* Literal */ && t & 224 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) return true; - if (source.flags & 32768 /* Object */ && target.flags & 16777216 /* NonPrimitive */) + if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) + if (s & 1 /* Any */) return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -33378,29 +33888,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33789,10 +34276,10 @@ var ts; } } else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -33901,24 +34388,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34038,7 +34539,7 @@ var ts; // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6 /* Synthetic */) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -34065,13 +34566,13 @@ var ts; } // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is the constructor type for an abstract class @@ -34120,8 +34621,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -34215,8 +34716,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -34224,8 +34725,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34251,7 +34752,7 @@ var ts; return getUnionType(types, /*subtypeReduction*/ true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -34299,27 +34800,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -34331,8 +34832,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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -34342,35 +34843,35 @@ var ts; // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : type.flags & 7406 /* PossiblyFalsy */; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) - types.push(voidType); - if (flags & 2048 /* Undefined */) - types.push(undefinedType); - if (flags & 4096 /* Null */) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 /* String */ ? emptyStringType : + type.flags & 4 /* Number */ ? zeroType : + type.flags & 8 /* Boolean */ || type === falseType ? falseType : + type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & 32 /* StringLiteral */ && type.value === "" || + type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + return missing === 0 ? type : + missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } @@ -34537,7 +35038,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -34622,7 +35123,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -34655,20 +35156,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -34683,7 +35174,7 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -34800,26 +35291,29 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768 /* Object */) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 32768 /* Object */ && + !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -34908,8 +35402,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35005,7 +35499,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35018,11 +35512,13 @@ var ts; // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35091,7 +35587,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } @@ -35154,8 +35650,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -35173,15 +35669,16 @@ var ts; return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type.text === "0"; + if (flags & 64 /* NumberLiteral */) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; @@ -35388,7 +35885,7 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -35414,8 +35911,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35495,8 +35992,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35527,7 +36024,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -35553,7 +36050,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -35695,7 +36192,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36202,6 +36699,26 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 /* PropertyAccessExpression */ || + parent.kind === 181 /* CallExpression */ && parent.expression === node || + parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + } + function getDeclaredOrApparentType(symbol, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36268,7 +36785,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36309,7 +36826,7 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048 /* Undefined */); + getNullableType(type, 2048 /* Undefined */); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -36317,7 +36834,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37214,8 +37731,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -37329,7 +37846,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -37367,7 +37884,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -37518,6 +38035,8 @@ var ts; if (spread.flags & 32768 /* Object */) { // only set the symbol and flags if this is a (fresh) object type spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; spread.symbol = node.symbol; } return spread; @@ -37596,6 +38115,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37613,6 +38136,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37622,39 +38148,39 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. if (child.kind === 10 /* JsxText */) { @@ -37666,11 +38192,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37681,7 +38207,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37689,8 +38220,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37768,7 +38298,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37820,6 +38361,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37840,6 +38395,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37878,6 +38434,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -37947,7 +38504,7 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -38152,6 +38709,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38180,7 +38765,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38200,29 +38798,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; - } - if (getCheckFlags(s) & 6 /* Synthetic */) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : - 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216 /* Prototype */) { - return 4 /* Public */ | 32 /* Static */; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); } /** * Check whether the requested property access is valid. @@ -38233,11 +38813,11 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? node.name : node.right; - if (getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 256 /* 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; @@ -38335,42 +38915,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (getCheckFlags(prop) & 1 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -38407,7 +38951,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -38426,6 +38970,126 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455 /* Value */); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -38548,7 +39212,16 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183 /* TaggedTemplateExpression */) { checkExpression(node.template); } @@ -38579,8 +39252,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -38688,7 +39361,7 @@ var ts; // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -39059,7 +39732,7 @@ var ts; case 71 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { @@ -39169,7 +39842,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; var isDecorator = node.kind === 147 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -39199,7 +39872,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -39300,7 +39973,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -39308,14 +39981,45 @@ var ts; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } // 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 that anySignature. @@ -39323,8 +40027,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -39334,14 +40038,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -39509,7 +40205,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39676,8 +40372,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -39854,7 +40550,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return getNullableType(type, 2048 /* Undefined */); } } return type; @@ -39920,11 +40616,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -40055,7 +40751,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40251,7 +40947,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40278,7 +40974,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { 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); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40291,7 +40987,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -40304,8 +41000,8 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || - symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */); @@ -40392,7 +41088,7 @@ var ts; return silentNeverType; } if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37 /* PlusToken */: @@ -40439,8 +41135,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40457,8 +41153,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -40467,8 +41163,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -40513,7 +41209,7 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { @@ -40808,7 +41504,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; @@ -40868,7 +41564,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? @@ -40961,12 +41657,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41012,9 +41711,9 @@ var ts; } switch (node.kind) { case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; case 86 /* FalseKeyword */: @@ -41079,7 +41778,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); } return false; } @@ -41424,17 +42123,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41457,7 +42157,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41476,7 +42176,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41595,7 +42295,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41683,7 +42383,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41840,7 +42541,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -41883,7 +42584,7 @@ var ts; } // Check if we're indexing with a numeric type and the object type is a generic // type with a constraint that has a numeric index signature. - if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 340 /* NumberLike */)) { + if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 84 /* NumberLike */)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { return type; @@ -41943,16 +42644,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41963,7 +42664,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42087,7 +42788,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42101,8 +42802,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42160,12 +42861,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42480,7 +43182,9 @@ var ts; * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -42490,6 +43194,57 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167 /* IntersectionType */: + case 166 /* UnionType */: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -42520,7 +43275,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -42529,15 +43284,15 @@ var ts; case 154 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149 /* PropertyDeclaration */: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146 /* Parameter */: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -42671,15 +43426,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42759,7 +43515,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42827,7 +43583,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42841,7 +43597,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43107,7 +43863,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43222,11 +43978,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43609,7 +44368,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43831,13 +44590,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44076,7 +44838,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -44109,7 +44871,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -44132,15 +44894,11 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; @@ -44160,7 +44918,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44247,97 +45005,88 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); - var autoValue = 0; // set to undefined when enum member is non-constant - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384 /* EnumValuesComputed */; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192 /* PrefixUnaryExpression */: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + 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); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192 /* PrefixUnaryExpression */: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37 /* PlusToken */: return value_1; case 38 /* MinusToken */: return -value_1; case 52 /* TildeToken */: return ~value_1; } - return undefined; - case 194 /* BinaryExpression */: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49 /* BarToken */: return left | right; case 48 /* AmpersandToken */: return left & right; case 46 /* GreaterThanGreaterThanToken */: return left >> right; @@ -44350,81 +45099,53 @@ var ts; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; } - return undefined; - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(e); - return +e.text; - case 185 /* ParenthesizedExpression */: - return evalConstant(e.expression); - case 71 /* Identifier */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71 /* Identifier */) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = expr.kind === 179 /* PropertyAccessExpression */ ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180 /* ElementAccessExpression */) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9 /* StringLiteral */) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - var current = expression; - while (current) { - if (current.kind === 71 /* Identifier */) { - break; - } - else if (current.kind === 179 /* PropertyAccessExpression */) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8 /* EnumMember */)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 /* Identifier */ || + node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9 /* StringLiteral */; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -44455,7 +45176,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -44714,6 +45435,10 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === 246 /* ExportSpecifier */ && compilerOptions.isolatedModules && !(target.flags & 107455 /* Value */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -45436,7 +46161,7 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -45564,7 +46289,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -45654,16 +46379,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { @@ -45981,7 +46706,7 @@ var ts; else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178 /* StringLike */)) { @@ -46010,7 +46735,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096 /* AddUndefined */) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -46022,15 +46747,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46116,7 +46832,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46284,7 +46999,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46311,9 +47026,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -47419,6 +48135,19 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + if (name.parent.propertyName) { + return true; + } + // falls through + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); /// /// @@ -47556,53 +48285,63 @@ var ts; if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { return node; } - switch (node.kind) { - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 298 /* EndOfDeclarationMarker */: - case 247 /* MissingDeclaration */: - // No need to visit nodes with no children. - return node; + switch (kind) { // Names + case 71 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - // Signatures and Signature Elements - case 160 /* FunctionType */: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155 /* CallSignature */: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150 /* MethodSignature */: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157 /* IndexSignature */: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Signature elements + case 145 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 148 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 159 /* TypeReference */: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 158 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163 /* TypeLiteral */: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167 /* IntersectionType */: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170 /* TypeOperator */: @@ -47613,22 +48352,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - // Type Declarations - case 145 /* TypeParameter */: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - // Type members - case 148 /* PropertySignature */: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* MethodDeclaration */: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); // Binding patterns case 174 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); @@ -47667,12 +48390,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: @@ -47689,6 +48412,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc case 205 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); @@ -47735,6 +48460,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233 /* ModuleDeclaration */: @@ -47743,6 +48472,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238 /* ImportDeclaration */: @@ -47769,8 +48500,6 @@ var ts; // JSX case 249 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxAttributes */: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251 /* JsxOpeningElement */: @@ -47779,6 +48508,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256 /* JsxExpression */: @@ -47808,7 +48539,10 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: + // No need to visit nodes with no children. return node; } } @@ -47884,6 +48618,13 @@ var ts; result = reduceNode(node.expression, cbNode, result); break; // Type member + case 148 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -48234,6 +48975,9 @@ var ts; case 296 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; + case 297 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -48856,7 +49600,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -50275,21 +51019,17 @@ var ts; return ts.createIdentifier("Object"); } function serializeUnionOrIntersectionType(node) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || @@ -50819,7 +51559,12 @@ var ts; // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -50894,10 +51639,12 @@ var ts; * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { - // Emit a variable statement for the module. - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ]); + ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -51154,7 +51901,7 @@ var ts; function visitExportDeclaration(node) { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -51583,7 +52330,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -51920,7 +52667,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -51988,21 +52735,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52152,6 +52893,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52159,24 +52903,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52187,13 +52928,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52479,12 +53214,22 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; @@ -52498,11 +53243,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -52532,7 +53277,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -53017,7 +53762,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -53224,7 +53969,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -54502,12 +55247,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26 /* CommaToken */, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -55842,7 +56588,7 @@ var ts; if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -56276,8 +57022,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } currentSourceFile = node; @@ -58730,7 +59475,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -59025,9 +59770,9 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: // This visitor does not descend into the tree, as export/import statements @@ -59826,9 +60571,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60716,9 +61459,9 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -61200,7 +61943,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -61363,7 +62106,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(300 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -61428,7 +62171,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** * Enables expression substitutions in the pretty printer for the provided SyntaxKind. @@ -62377,7 +63120,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62413,11 +63156,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62844,12 +63587,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62862,24 +63604,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62891,12 +63639,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62969,7 +63711,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63206,7 +63948,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -63305,7 +64047,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63317,12 +64059,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63339,7 +64075,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63354,6 +64090,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63361,15 +64110,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63390,7 +64146,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -63449,7 +64205,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) { + else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || + (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -63458,7 +64215,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -63668,6 +64425,11 @@ var ts; write("["); } else { + if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { write("new "); @@ -63974,7 +64736,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } @@ -64158,7 +64920,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -64195,7 +64957,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -64283,7 +65045,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -64362,7 +65126,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -64580,7 +65344,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -64603,7 +65367,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions case 177 /* ArrayLiteralExpression */: @@ -64668,6 +65432,8 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* CommaListExpression */: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -64706,6 +65472,7 @@ var ts; // function emitIdentifier(node) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // // Names @@ -64734,6 +65501,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -64854,7 +65622,10 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65 /* TypeLiteralMembers */); + // If the literal is empty, do not add spaces between braces. + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); + } write("}"); } function emitArrayType(node) { @@ -64892,9 +65663,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -64905,8 +65682,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -64922,7 +65704,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); + emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); write("}"); } } @@ -65006,7 +65788,7 @@ var ts; // check if constant enum value is integer var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -65109,7 +65891,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -65837,6 +66619,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272 /* CommaListElements */); + } /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -66118,6 +66903,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -66300,7 +67094,9 @@ var ts; if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -66580,14 +67376,17 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -66814,6 +67613,90 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + // 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) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + 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. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -66863,6 +67746,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -66919,7 +67803,8 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); @@ -66978,7 +67863,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67016,76 +67902,100 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { - // if old program state is not supplied and file does not contain locally defined ambient modules - // then the best we can do is fallback to the default logic + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile); } - // at this point we know that either + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occured during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules - // OR // - old program state is available - // OR - // - both of items above - // With this it is possible that we can tell how some module names from the initial list will be resolved - // without doing actual resolution (in particular if some name was resolved to ambient module). - // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` - // since we don't want to resolve them again. - // this is a list of modules for which we cannot predict resolution so they should be actually resolved + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ var unknownModuleNames; - // this is a list of combined results assembles from predicted and resolved results. - // Order in this list matches the order in the original list of module names `moduleNames` which is important - // so later we can split results to resolutions of modules and resolutions of module augmentations. + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ var result; - // a transient placeholder that is used to mark predicted resolution in the result list + /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // module name is known to be resolved to ambient module if - // - module name is contained in the list of ambient modules that are locally declared in the file - // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // If we want to reuse resolutions more aggressively, we can refine this to check for whether the + // text of the corresponding modulenames has changed. + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file // (so the same module declaration will land in the new program) - var isKnownToResolveToAmbientModule = false; + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - // found a first module name for which result can be prediced - // this means that this module name should not be passed to `resolveModuleNamesWorker`. - // We'll use a separate list for module names that are definitely unknown. - result = new Array(moduleNames.length); - // copy all module names that appear before the current one in the list - // since they are known to be unknown - unknownModuleNames = moduleNames.slice(0, i); - } - // mark prediced resolution in the result list - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - // found unknown module name and we are already using separate list for those - add it to the list - unknownModuleNames.push(moduleName); + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - // we've looked throught the list but have not seen any predicted resolution - // use default logic - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; - // combine results of resolutions and predicted results + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -67094,16 +68004,15 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { // module used to be resolved to file - ignore it return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -67123,84 +68032,90 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0 /* Not */; } // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); // there is an old program, check if we can reuse its structure var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { + // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check tripleslash references if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - // file has no changes - use it as is - newSourceFile = oldSourceFile; - } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); // try to verify results of module resolution for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -67209,12 +68124,16 @@ var ts; // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { @@ -67227,8 +68146,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return { @@ -67616,7 +68534,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -67647,7 +68565,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -67694,7 +68611,7 @@ var ts; } break; case 233 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -67705,7 +68622,7 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -67734,45 +68651,52 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -67925,11 +68849,11 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -67986,7 +68910,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -68084,12 +69008,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -69266,57 +70190,37 @@ var ts; * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; + } + if (exclude) { + json.exclude = exclude; + } + if (files) { + json.files = files; + } + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; + } + return options; + })(); + options = ts.extend(existingOptions, options); + options.configFilePath = configFileName; // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } - options = ts.extend(existingOptions, options); - options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -69326,39 +70230,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -69389,9 +70261,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -69409,9 +70278,73 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, // Usually a string. + host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -70046,7 +70979,6 @@ var ts; case 148 /* PropertySignature */: case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: - case 264 /* EnumMember */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: case 152 /* Constructor */: @@ -70063,9 +70995,11 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 264 /* EnumMember */: case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; + case 232 /* EnumDeclaration */: + return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -70082,7 +71016,7 @@ var ts; case 238 /* ImportDeclaration */: case 243 /* ExportAssignment */: case 244 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; // An external module can be a Value case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; @@ -70241,7 +71175,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -70256,36 +71190,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -70623,45 +71527,25 @@ var ts; // exit early return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } // find the child that contains 'position' - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -70788,10 +71672,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; /** * returns true if the position is in between the open and close elements of an JSX expression. */ @@ -70830,13 +71710,27 @@ var ts; } ts.isInTemplateString = isInTemplateString; /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -70847,16 +71741,14 @@ var ts; // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + return kind === 2 /* SingleLineCommentTrivia */ || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === 47 /* slash */ && text.charCodeAt(end - 2) === 42 /* asterisk */); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); // First, we have to see if this position actually landed in a comment. @@ -70979,6 +71871,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -71027,25 +71922,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119 /* AnyKeyword */: @@ -71326,8 +72223,8 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; @@ -71422,7 +72319,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -71431,8 +72328,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72441,8 +73338,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -72733,7 +73630,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; @@ -72763,14 +73660,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -72826,8 +73725,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -72917,10 +73816,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -72948,9 +73848,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384 /* TypeParameter */) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -72958,16 +73859,20 @@ var ts; if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -73032,7 +73937,7 @@ var ts; log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); // Completion not allowed inside comments, bail out if this is the case - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -73083,7 +73988,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -73171,6 +74076,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -73204,7 +74110,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; @@ -73255,6 +74161,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -73264,6 +74171,11 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { @@ -73437,16 +74349,16 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { @@ -73469,7 +74381,11 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -73480,10 +74396,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -73525,6 +74437,53 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32 /* Static */) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -73561,6 +74520,44 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17 /* OpenBraceToken */: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number; | } + case 26 /* CommaToken */: + case 25 /* SemicolonToken */: + // class c { method() { } | } + case 18 /* CloseBraceToken */: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + // class c { method() { } | method2() { } } + if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -73673,7 +74670,7 @@ var ts; containingNodeKind === 231 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; + return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 146 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && @@ -73686,13 +74683,17 @@ var ts; return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || containingNodeKind === 240 /* NamespaceImport */; + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: case 89 /* FunctionKeyword */: case 104 /* VarKeyword */: - case 125 /* GetKeyword */: - case 135 /* SetKeyword */: case 91 /* ImportKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: @@ -73700,6 +74701,12 @@ var ts; case 138 /* TypeKeyword */: return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -73742,7 +74749,7 @@ var ts; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -73776,7 +74783,7 @@ var ts; continue; } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -73790,12 +74797,55 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 149 /* PropertyDeclaration */ && + m.kind !== 151 /* MethodDeclaration */ && + m.kind !== 153 /* GetAccessor */ && + m.kind !== 154 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + var mIsStatic = ts.hasModifier(m, 32 /* Static */); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8 /* Private */); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24 /* NonPublicAccessibilityModifier */); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * @@ -73807,7 +74857,7 @@ var ts; for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253 /* JsxAttribute */) { @@ -73816,6 +74866,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } /** * Get the name to be display in completion from a given symbol. @@ -73868,6 +74921,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 123 /* ConstructorKeyword */: + case 131 /* ReadonlyKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 120 /* AsyncKeyword */: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -73884,9 +74958,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -73898,8 +74972,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -74693,6 +75767,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74771,11 +75848,42 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -74799,7 +75907,7 @@ var ts; } /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -74827,26 +75935,20 @@ var ts; } } }); - if (sourceFile.flags & 65536 /* JavaScriptFile */) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 /* ImportDeclaration */ || decl.kind === 244 /* ExportDeclaration */) { - return decl; + switch (decl.kind) { + case 181 /* CallExpression */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return decl; + case 248 /* ExternalModuleReference */: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248 /* ExternalModuleReference */); - return decl.parent; } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. @@ -74983,12 +76085,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); - ts.Debug.assert(!!name); - return name; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { @@ -75035,12 +76138,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. @@ -75051,44 +76155,46 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -75098,10 +76204,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -75242,7 +76344,7 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265 /* SourceFile */) { return undefined; @@ -75253,6 +76355,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -75263,13 +76366,60 @@ var ts; // Can't have references to something that we have no symbol for. return undefined; } - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9 /* StringLiteral */) { + return false; + } + switch (node.parent.kind) { + case 233 /* ModuleDeclaration */: + case 248 /* ExternalModuleReference */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return true; + case 181 /* CallExpression */: + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265 /* 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 233 /* ModuleDeclaration */: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { @@ -75510,7 +76660,11 @@ var ts; // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. @@ -75542,16 +76696,12 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -75561,28 +76711,27 @@ var ts; // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case 71 /* Identifier */: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -75604,10 +76753,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -75738,7 +76885,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76004,9 +77151,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; @@ -76058,13 +77205,13 @@ var ts; if (searchSpaceNode.kind === 265 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -76110,10 +77257,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -76121,8 +77268,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); @@ -76319,20 +77466,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -76501,17 +77648,10 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 71 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 242 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 241 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -76530,16 +77670,6 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -76550,16 +77680,10 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -76579,13 +77703,13 @@ var ts; return undefined; } if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -76593,6 +77717,28 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239 /* ImportClause */: + case 237 /* ImportEqualsDeclaration */: + return true; + case 242 /* ImportSpecifier */: + return declaration.parent.kind === 241 /* NamedImports */; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -76663,7 +77809,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -76691,7 +77837,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -76763,6 +77909,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -76773,8 +77920,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -77257,8 +78402,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. @@ -77301,17 +78446,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77340,8 +78488,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77379,6 +78528,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77388,8 +78538,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77641,8 +78791,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77731,9 +78881,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77750,7 +78900,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -79128,138 +80278,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -81588,9 +82633,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -81601,18 +82646,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -81620,51 +82661,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, + 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81689,6 +82759,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -81704,123 +82776,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true - // so if the option is undefined, we should treat it as true as well - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -82074,7 +83032,7 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -82171,7 +83129,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -83069,9 +84027,7 @@ var ts; if (node.kind === 20 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -83665,7 +84621,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); @@ -83694,27 +84650,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited @@ -83759,6 +84696,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -83827,14 +84774,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -83858,6 +84805,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -83924,7 +84916,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -84014,7 +85007,7 @@ var ts; /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); - var indexSignature = ts.createIndexSignatureDeclaration( + var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -84031,6 +85024,60 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 793064 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 107455 /* Value */; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84232,131 +85279,135 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - switch (token.parent.kind) { - case 226 /* VariableDeclaration */: - switch (token.parent.parent.parent.kind) { - case 214 /* ForStatement */: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216 /* ForOfStatement */: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return undefined; - case 260 /* CatchClause */: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - // TODO: #14885 - // falls through - case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); - case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); - } - else { - // delete import specifier - return deleteNodeInList(token.parent); - } - // handle case where "import d, * as ns from './file'" - // or "'import {a, b as ns} from './file'" - case 239 /* ImportClause */: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - // import |d,| * as ns from './file' - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226 /* VariableDeclaration */: + return deleteVariableDeclaration(token.parent); + case 145 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + // handle case where 'import a = A;' + case 237 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); + return deleteNode(importEquals); + case 242 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); + return deleteNode(importSpec); + } + else { + // delete import specifier + return deleteNodeInList(token.parent); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 239 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + // import |d,| * as ns from './file' + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + // token.parent is a variableDeclaration + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214 /* ForStatement */: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -84388,6 +85439,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -84485,400 +85545,393 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238 /* ImportDeclaration */) { + return node; } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + // insert after any existing imports + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + : isNamespaceImport + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - // if node_modules folder is in this folder or any of its parent folder, no need to keep it. - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -85010,7 +86063,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85068,7 +86121,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -85124,7 +86177,7 @@ var ts; /*returnType*/ undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration( + return ts.createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } @@ -85147,6 +86200,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -85156,6 +86210,188 @@ var ts; /// /// /// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 /* Function */ && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186 /* FunctionExpression */: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + case 187 /* ArrowFunction */: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 207 /* Block */) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + default: + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -85182,11 +86418,15 @@ var ts; /// /// /// +/// /// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; + /* @internal */ + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : @@ -85571,13 +86811,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -85962,7 +87203,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -85987,10 +87228,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - // Ensure rules are initialized and up to date wrt to formatting options - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -86283,7 +87520,7 @@ var ts; /// Goto implementation function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -86300,7 +87537,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -86333,11 +87570,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { @@ -86640,8 +87877,7 @@ var ts; var matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -86729,11 +87965,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -86859,20 +88119,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -88130,6 +89390,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -88304,3 +89567,5 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "2.4"; + +//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 01d5540db54..df00c45de24 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -359,9 +359,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -474,6 +475,10 @@ declare namespace ts { type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ text: string; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; @@ -491,9 +496,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +511,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +519,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +532,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +544,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +553,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +575,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +597,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +605,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +957,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1016,7 +1023,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1076,6 +1083,13 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1197,7 +1211,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1224,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1252,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1311,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1344,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1481,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1706,11 +1720,11 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1720,38 +1734,48 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1912,18 +1936,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1935,15 +1959,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } enum ObjectFlags { Class = 1, @@ -1988,7 +2014,7 @@ declare namespace ts { */ interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -2024,7 +2050,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { @@ -2059,9 +2085,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2329,6 +2355,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2611,14 +2638,14 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2709,6 +2736,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -2727,58 +2755,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2786,6 +2775,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2827,7 +2855,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2847,16 +2875,15 @@ 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 createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2888,10 +2915,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2900,6 +2936,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2930,20 +2968,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2976,6 +3014,8 @@ declare namespace ts { */ function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -3040,11 +3080,11 @@ declare namespace ts { /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; /** * Sets the constant value to emit for an expression. */ - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; /** * Adds an EmitHelper to a node. */ @@ -3069,17 +3109,13 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** Array that is only intended to be pushed to, never read. */ - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -3218,6 +3254,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -3246,9 +3283,10 @@ declare namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3422,6 +3460,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3492,6 +3532,10 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -4006,6 +4050,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 4fe0eb9bf25..a73895f4f74 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -365,10 +365,11 @@ var ts; // Transformation nodes SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -512,6 +513,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); /** Return code used by getEmitOutput function to indicate status of the function */ var ExitStatus; (function (ExitStatus) { @@ -527,12 +535,23 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -677,6 +696,12 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -751,7 +776,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -761,7 +786,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; @@ -770,7 +795,7 @@ var ts; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; @@ -1119,6 +1144,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1138,17 +1164,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1450,12 +1481,6 @@ var ts; return undefined; } ts.forEach = forEach; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1477,6 +1502,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1704,6 +1738,35 @@ var ts; return result; } ts.flatMap = flatMap; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2881,6 +2944,11 @@ var ts; } ts.startsWith = startsWith; /* @internal */ + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -4058,6 +4126,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -4165,7 +4234,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -4360,6 +4429,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4655,6 +4732,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4700,6 +4778,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4781,6 +4861,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -5443,9 +5526,10 @@ var ts; ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6654,9 +6738,7 @@ var ts; ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -6849,28 +6931,30 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8 /* NumericLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -7099,10 +7183,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 /* EnumDeclaration */ && isConst(node); } @@ -7382,6 +7462,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151 /* MethodDeclaration */: @@ -7638,6 +7727,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183 /* TaggedTemplateExpression */) { return node.tag; @@ -8230,21 +8323,46 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 71 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { - return false; + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 /* ImportSpecifier */ || parent.kind === 246 /* ExportSpecifier */) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0 /* None */: + case 2 /* ModuleExports */: + return undefined; + case 1 /* ExportsProperty */: + if (lhs.kind === 71 /* Identifier */) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4 /* ThisProperty */: + case 5 /* Property */: + return lhs.name; + case 3 /* PrototypeProperty */: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && @@ -8357,21 +8475,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -8399,12 +8515,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8457,7 +8574,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -8740,6 +8858,8 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; + case 297 /* CommaListExpression */: + return 0; default: return -1; } @@ -8853,14 +8973,15 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -8949,7 +9070,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -9015,7 +9136,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; /** @@ -9579,13 +9700,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0 /* CarriageReturnLineFeed */) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; } - else if (options.newLine === 1 /* LineFeed */) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -9913,10 +10034,6 @@ var ts; return node.kind === 71 /* Identifier */; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; @@ -9989,9 +10106,20 @@ var ts; || kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */ || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */; + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 /* ConstructSignature */ + || kind === 155 /* CallSignature */ + || kind === 148 /* PropertySignature */ + || kind === 150 /* MethodSignature */ + || kind === 157 /* IndexSignature */ + || kind === 247 /* MissingDeclaration */; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 /* PropertyAssignment */ @@ -10209,6 +10337,7 @@ var ts; || kind === 198 /* SpreadElement */ || kind === 202 /* AsExpression */ || kind === 200 /* OmittedExpression */ + || kind === 297 /* CommaListExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -10297,6 +10426,10 @@ var ts; return node.kind === 237 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239 /* ImportClause */; } @@ -10319,6 +10452,10 @@ var ts; return node.kind === 246 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; } @@ -10390,8 +10527,8 @@ var ts; || kind === 213 /* WhileStatement */ || kind === 220 /* WithStatement */ || kind === 295 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + || kind === 299 /* EndOfDeclarationMarker */ + || kind === 298 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -10517,6 +10654,49 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10983,16 +11163,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - // Identifiers - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable) { @@ -11087,240 +11275,13 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - // Type Elements - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - // Types - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173 /* LiteralType */); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159 /* TypeReference */); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158 /* TypePredicate */); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162 /* TypeQuery */); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164 /* ArrayType */); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163 /* TypeLiteral */); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165 /* TupleType */); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172 /* MappedType */); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170 /* TypeOperator */); - typeOperatorNode.operator = 127 /* KeyOfKeyword */; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171 /* IndexedAccessType */); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; - // Type Declarations + // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145 /* TypeParameter */); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -11331,44 +11292,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - // Signature elements - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148 /* PropertySignature */); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157 /* IndexSignature */); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; - // Signature elements function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146 /* Parameter */); node.decorators = asNodeArray(decorators); @@ -11405,7 +11328,27 @@ var ts; : node; } ts.updateDecorator = updateDecorator; - // Type members + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); @@ -11427,7 +11370,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -11440,7 +11400,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -11450,7 +11410,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11518,6 +11478,251 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164 /* ArrayType */); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170 /* TypeOperator */); + node.operator = 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174 /* ObjectBindingPattern */); @@ -11565,9 +11770,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11580,9 +11784,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11632,9 +11835,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11824,10 +12027,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11954,6 +12157,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205 /* TemplateSpan */); @@ -11969,6 +12185,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { var block = createSynthesizedNode(207 /* Block */); @@ -11979,7 +12199,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11999,35 +12219,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209 /* EmptyStatement */); } @@ -12246,6 +12437,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); @@ -12294,6 +12518,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); @@ -12314,7 +12580,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233 /* ModuleDeclaration */); - node.flags |= flags; + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -12355,6 +12621,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); @@ -12385,7 +12663,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12573,19 +12852,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254 /* JsxAttributes */); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253 /* JsxAttribute */); node.name = name; @@ -12600,6 +12866,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); node.expression = expression; @@ -12626,20 +12904,6 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; // Clauses - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12648,10 +12912,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12661,12 +12925,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260 /* CatchClause */); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12675,10 +12951,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; // Property assignments @@ -12691,10 +12967,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12705,10 +12981,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12718,10 +12994,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; // Enum @@ -12833,7 +13108,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12845,7 +13120,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12874,6 +13149,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266 /* Bundle */); node.sourceFiles = sourceFiles; @@ -13250,7 +13548,25 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // Compound nodes + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -13512,7 +13828,11 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13686,9 +14006,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13846,16 +14167,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -14131,6 +14442,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; /** * Clones a series of not-emitted expressions with a new inner expression. * @@ -14311,7 +14650,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15079,6 +15418,8 @@ var ts; return visitNode(cbNode, node.expression); case 247 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 297 /* CommaListExpression */: + return visitNodes(cbNodes, node.elements); case 249 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -20465,6 +20806,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -21452,7 +21795,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -21480,7 +21823,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -21517,12 +21860,13 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21530,7 +21874,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21674,9 +22018,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -23592,7 +23936,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -23611,7 +23955,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23626,7 +23970,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23639,7 +23983,7 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -24526,13 +24870,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -24860,6 +25202,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25062,13 +25406,24 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -25099,7 +25454,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -25462,6 +25816,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -25613,13 +25968,16 @@ var ts; // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -25702,11 +26060,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -25972,16 +26332,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26063,9 +26423,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -26073,7 +26430,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -26109,7 +26466,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26205,7 +26563,11 @@ var ts; // 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 // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; var propertyWithInvalidInitializer; @@ -26215,7 +26577,7 @@ var ts; loop: while (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 = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { // symbol lookup restrictions for function-like declarations @@ -26286,12 +26648,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { break loop; } break; case 232 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; @@ -26306,7 +26668,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -26316,7 +26678,7 @@ var ts; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -26351,7 +26713,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -26412,7 +26774,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -26422,7 +26784,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -26541,6 +26913,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -26573,13 +26949,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -26595,7 +26971,7 @@ var ts; if (node.kind === 237 /* ImportEqualsDeclaration */) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238 /* ImportDeclaration */; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -26719,10 +27095,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); @@ -26738,7 +27114,7 @@ var ts; case 242 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 243 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236 /* NamespaceExportDeclaration */: @@ -26887,7 +27263,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26909,6 +27285,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; @@ -26978,7 +27359,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -27128,7 +27508,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32 /* StringLiteral */, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started @@ -27458,34 +27838,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -27495,15 +27900,14 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } if (type.flags & 1 /* Any */) { @@ -27518,23 +27922,25 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 16 /* Enum */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + } + if (type.flags & 272 /* EnumLike */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256 /* EnumLiteral */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & 1024 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } @@ -27554,8 +27960,8 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -27566,39 +27972,31 @@ var ts; ts.Debug.assert(!!(type.flags & 32768 /* Object */)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3 /* ClassOrInterface */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - // TODO(aozgaa): handle type arguments. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & 16384 /* TypeParameter */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536 /* Union */) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166 /* UnionType */, unionTypeNodes); + if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { + var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072 /* Intersection */) { - return ts.createUnionOrIntersectionTypeNode(167 /* IntersectionType */, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); // The type is an object literal type. @@ -27606,35 +28004,23 @@ var ts; } if (type.flags & 262144 /* Index */) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -27643,14 +28029,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); } else if (ts.contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27696,41 +28082,53 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(/*members*/ undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -27738,7 +28136,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27751,48 +28149,72 @@ var ts; // 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)) { - var qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, /*right*/ undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71 /* Identifier */) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71 /* Identifier */) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); } var properties = resolvedType.properties; if (!properties) { @@ -27801,86 +28223,131 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 136 /* StringKeyword */ : 133 /* NumberKeyword */); - var name = ts.getNameFromIndexInfo(indexInfo); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration( + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - // TODO(aozgaa): In the future, check initializer accessibility. - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24 /* DotDotDotToken */), - // Clone name to remove trivia. - ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55 /* QuestionToken */), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048 /* Undefined */); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0 /* None */, /*endOfChain*/ true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -27888,19 +28355,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -27909,20 +28375,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -27954,28 +28410,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -27993,12 +28450,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -28034,13 +28493,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28097,7 +28557,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -28180,12 +28640,17 @@ var ts; else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -28541,7 +29006,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -28808,10 +29273,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246 /* ExportSpecifier */) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -28954,7 +29416,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -29070,7 +29532,7 @@ var ts; return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -29173,6 +29635,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : @@ -29189,17 +29652,25 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536 /* JavaScriptFile */) { - // If there is a JSDoc type, use it - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding @@ -29449,7 +29920,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; } } } @@ -29512,7 +29983,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -29711,6 +30182,7 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && @@ -29718,7 +30190,7 @@ var ts; // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; @@ -29902,77 +30374,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 /* NumericLiteral */ || + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 71 /* Identifier */ && !!symbol.exports.get(expr.text); + expr.kind === 71 /* Identifier */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256 /* EnumLiteral */); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536 /* Union */; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 65536 /* Union */) { + enumType_1.flags |= 256 /* EnumLiteral */; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -30219,7 +30694,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -30306,8 +30781,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -30481,7 +30956,7 @@ var ts; // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); @@ -30613,6 +31088,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190 /* Primitive */) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : @@ -30674,8 +31170,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -30731,7 +31227,7 @@ var ts; var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : @@ -30746,12 +31242,12 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -30823,7 +31319,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -31231,8 +31727,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -31367,8 +31864,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_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -31399,7 +31896,7 @@ var ts; return ts.length(type.target.typeParameters); } // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -31414,7 +31911,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -31437,7 +31934,7 @@ var ts; // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -31449,7 +31946,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -31489,14 +31985,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 /* Value */ && node.kind === 277 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In @@ -31559,10 +32056,7 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. @@ -31571,6 +32065,9 @@ var ts; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -31812,14 +32309,14 @@ 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, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31827,8 +32324,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -31959,8 +32456,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 addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -32024,9 +32521,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -32056,12 +32553,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? - indexType.text : + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -32076,11 +32573,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { @@ -32105,7 +32602,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -32258,7 +32755,7 @@ var ts; var rightProp = _a[_i]; // we approximate own properties as non-methods plus methods that are inside the object literal var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -32275,11 +32772,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { + if (rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -32306,15 +32803,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32325,11 +32823,17 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -32593,7 +33097,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { var links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases @@ -33087,29 +33591,27 @@ var ts; type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8 /* EnumMember */) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33120,42 +33622,50 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + if (t & 1 /* Any */ || s & 8192 /* Never */) return true; - if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) + if (s & 262178 /* StringLike */ && t & 2 /* String */) return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + if (s & 84 /* NumberLike */ && t & 4 /* Number */) return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { + if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 /* Literal */ && t & 224 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) return true; - if (source.flags & 32768 /* Object */ && target.flags & 16777216 /* NonPrimitive */) + if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) + if (s & 1 /* Any */) return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -33378,29 +33888,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33789,10 +34276,10 @@ var ts; } } else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -33901,24 +34388,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34038,7 +34539,7 @@ var ts; // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6 /* Synthetic */) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -34065,13 +34566,13 @@ var ts; } // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is the constructor type for an abstract class @@ -34120,8 +34621,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -34215,8 +34716,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -34224,8 +34725,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34251,7 +34752,7 @@ var ts; return getUnionType(types, /*subtypeReduction*/ true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -34299,27 +34800,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -34331,8 +34832,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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -34342,35 +34843,35 @@ var ts; // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : type.flags & 7406 /* PossiblyFalsy */; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) - types.push(voidType); - if (flags & 2048 /* Undefined */) - types.push(undefinedType); - if (flags & 4096 /* Null */) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 /* String */ ? emptyStringType : + type.flags & 4 /* Number */ ? zeroType : + type.flags & 8 /* Boolean */ || type === falseType ? falseType : + type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & 32 /* StringLiteral */ && type.value === "" || + type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + return missing === 0 ? type : + missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } @@ -34537,7 +35038,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -34622,7 +35123,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -34655,20 +35156,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -34683,7 +35174,7 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -34800,26 +35291,29 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768 /* Object */) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 32768 /* Object */ && + !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -34908,8 +35402,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35005,7 +35499,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35018,11 +35512,13 @@ var ts; // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35091,7 +35587,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } @@ -35154,8 +35650,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -35173,15 +35669,16 @@ var ts; return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type.text === "0"; + if (flags & 64 /* NumberLiteral */) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; @@ -35388,7 +35885,7 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -35414,8 +35911,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35495,8 +35992,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35527,7 +36024,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -35553,7 +36050,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -35695,7 +36192,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36202,6 +36699,26 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 /* PropertyAccessExpression */ || + parent.kind === 181 /* CallExpression */ && parent.expression === node || + parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + } + function getDeclaredOrApparentType(symbol, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36268,7 +36785,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36309,7 +36826,7 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048 /* Undefined */); + getNullableType(type, 2048 /* Undefined */); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -36317,7 +36834,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37214,8 +37731,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -37329,7 +37846,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -37367,7 +37884,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -37518,6 +38035,8 @@ var ts; if (spread.flags & 32768 /* Object */) { // only set the symbol and flags if this is a (fresh) object type spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; spread.symbol = node.symbol; } return spread; @@ -37596,6 +38115,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37613,6 +38136,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37622,39 +38148,39 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. if (child.kind === 10 /* JsxText */) { @@ -37666,11 +38192,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37681,7 +38207,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37689,8 +38220,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37768,7 +38298,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37820,6 +38361,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37840,6 +38395,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37878,6 +38434,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -37947,7 +38504,7 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -38152,6 +38709,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38180,7 +38765,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38200,29 +38798,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; - } - if (getCheckFlags(s) & 6 /* Synthetic */) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : - 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216 /* Prototype */) { - return 4 /* Public */ | 32 /* Static */; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); } /** * Check whether the requested property access is valid. @@ -38233,11 +38813,11 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? node.name : node.right; - if (getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 256 /* 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; @@ -38335,42 +38915,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (getCheckFlags(prop) & 1 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -38407,7 +38951,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -38426,6 +38970,126 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455 /* Value */); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -38548,7 +39212,16 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183 /* TaggedTemplateExpression */) { checkExpression(node.template); } @@ -38579,8 +39252,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -38688,7 +39361,7 @@ var ts; // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -39059,7 +39732,7 @@ var ts; case 71 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { @@ -39169,7 +39842,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; var isDecorator = node.kind === 147 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -39199,7 +39872,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -39300,7 +39973,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -39308,14 +39981,45 @@ var ts; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } // 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 that anySignature. @@ -39323,8 +40027,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -39334,14 +40038,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -39509,7 +40205,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39676,8 +40372,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -39854,7 +40550,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return getNullableType(type, 2048 /* Undefined */); } } return type; @@ -39920,11 +40616,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -40055,7 +40751,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40251,7 +40947,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40278,7 +40974,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { 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); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40291,7 +40987,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -40304,8 +41000,8 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || - symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */); @@ -40392,7 +41088,7 @@ var ts; return silentNeverType; } if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37 /* PlusToken */: @@ -40439,8 +41135,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40457,8 +41153,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -40467,8 +41163,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -40513,7 +41209,7 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { @@ -40808,7 +41504,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; @@ -40868,7 +41564,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? @@ -40961,12 +41657,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41012,9 +41711,9 @@ var ts; } switch (node.kind) { case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; case 86 /* FalseKeyword */: @@ -41079,7 +41778,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); } return false; } @@ -41424,17 +42123,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41457,7 +42157,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41476,7 +42176,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41595,7 +42295,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41683,7 +42383,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41840,7 +42541,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -41883,7 +42584,7 @@ var ts; } // Check if we're indexing with a numeric type and the object type is a generic // type with a constraint that has a numeric index signature. - if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 340 /* NumberLike */)) { + if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 84 /* NumberLike */)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { return type; @@ -41943,16 +42644,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41963,7 +42664,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42087,7 +42788,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42101,8 +42802,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42160,12 +42861,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42480,7 +43182,9 @@ var ts; * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -42490,6 +43194,57 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167 /* IntersectionType */: + case 166 /* UnionType */: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -42520,7 +43275,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -42529,15 +43284,15 @@ var ts; case 154 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149 /* PropertyDeclaration */: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146 /* Parameter */: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -42671,15 +43426,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42759,7 +43515,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42827,7 +43583,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42841,7 +43597,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43107,7 +43863,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43222,11 +43978,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43609,7 +44368,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43831,13 +44590,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44076,7 +44838,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -44109,7 +44871,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -44132,15 +44894,11 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; @@ -44160,7 +44918,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44247,97 +45005,88 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); - var autoValue = 0; // set to undefined when enum member is non-constant - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384 /* EnumValuesComputed */; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192 /* PrefixUnaryExpression */: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + 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); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192 /* PrefixUnaryExpression */: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37 /* PlusToken */: return value_1; case 38 /* MinusToken */: return -value_1; case 52 /* TildeToken */: return ~value_1; } - return undefined; - case 194 /* BinaryExpression */: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49 /* BarToken */: return left | right; case 48 /* AmpersandToken */: return left & right; case 46 /* GreaterThanGreaterThanToken */: return left >> right; @@ -44350,81 +45099,53 @@ var ts; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; } - return undefined; - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(e); - return +e.text; - case 185 /* ParenthesizedExpression */: - return evalConstant(e.expression); - case 71 /* Identifier */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71 /* Identifier */) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = expr.kind === 179 /* PropertyAccessExpression */ ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180 /* ElementAccessExpression */) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9 /* StringLiteral */) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - var current = expression; - while (current) { - if (current.kind === 71 /* Identifier */) { - break; - } - else if (current.kind === 179 /* PropertyAccessExpression */) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8 /* EnumMember */)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 /* Identifier */ || + node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9 /* StringLiteral */; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -44455,7 +45176,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -44714,6 +45435,10 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === 246 /* ExportSpecifier */ && compilerOptions.isolatedModules && !(target.flags & 107455 /* Value */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -45436,7 +46161,7 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -45564,7 +46289,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -45654,16 +46379,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { @@ -45981,7 +46706,7 @@ var ts; else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178 /* StringLike */)) { @@ -46010,7 +46735,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096 /* AddUndefined */) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -46022,15 +46747,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46116,7 +46832,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46284,7 +46999,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46311,9 +47026,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -47419,6 +48135,19 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + if (name.parent.propertyName) { + return true; + } + // falls through + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); /// /// @@ -47556,53 +48285,63 @@ var ts; if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { return node; } - switch (node.kind) { - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 298 /* EndOfDeclarationMarker */: - case 247 /* MissingDeclaration */: - // No need to visit nodes with no children. - return node; + switch (kind) { // Names + case 71 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - // Signatures and Signature Elements - case 160 /* FunctionType */: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155 /* CallSignature */: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150 /* MethodSignature */: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157 /* IndexSignature */: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Signature elements + case 145 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 148 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 159 /* TypeReference */: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 158 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163 /* TypeLiteral */: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167 /* IntersectionType */: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170 /* TypeOperator */: @@ -47613,22 +48352,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - // Type Declarations - case 145 /* TypeParameter */: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - // Type members - case 148 /* PropertySignature */: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* MethodDeclaration */: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); // Binding patterns case 174 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); @@ -47667,12 +48390,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: @@ -47689,6 +48412,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc case 205 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); @@ -47735,6 +48460,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233 /* ModuleDeclaration */: @@ -47743,6 +48472,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238 /* ImportDeclaration */: @@ -47769,8 +48500,6 @@ var ts; // JSX case 249 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxAttributes */: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251 /* JsxOpeningElement */: @@ -47779,6 +48508,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256 /* JsxExpression */: @@ -47808,7 +48539,10 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: + // No need to visit nodes with no children. return node; } } @@ -47884,6 +48618,13 @@ var ts; result = reduceNode(node.expression, cbNode, result); break; // Type member + case 148 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -48234,6 +48975,9 @@ var ts; case 296 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; + case 297 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -48856,7 +49600,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -50275,21 +51019,17 @@ var ts; return ts.createIdentifier("Object"); } function serializeUnionOrIntersectionType(node) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || @@ -50819,7 +51559,12 @@ var ts; // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -50894,10 +51639,12 @@ var ts; * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { - // Emit a variable statement for the module. - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ]); + ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -51154,7 +51901,7 @@ var ts; function visitExportDeclaration(node) { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -51583,7 +52330,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -51920,7 +52667,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -51988,21 +52735,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52152,6 +52893,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52159,24 +52903,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52187,13 +52928,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52479,12 +53214,22 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; @@ -52498,11 +53243,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -52532,7 +53277,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -53017,7 +53762,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -53224,7 +53969,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -54502,12 +55247,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26 /* CommaToken */, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -55842,7 +56588,7 @@ var ts; if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -56276,8 +57022,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } currentSourceFile = node; @@ -58730,7 +59475,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -59025,9 +59770,9 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: // This visitor does not descend into the tree, as export/import statements @@ -59826,9 +60571,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60716,9 +61459,9 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -61200,7 +61943,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -61363,7 +62106,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(300 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -61428,7 +62171,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** * Enables expression substitutions in the pretty printer for the provided SyntaxKind. @@ -62377,7 +63120,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62413,11 +63156,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62844,12 +63587,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62862,24 +63604,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62891,12 +63639,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62969,7 +63711,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63206,7 +63948,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -63305,7 +64047,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63317,12 +64059,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63339,7 +64075,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63354,6 +64090,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63361,15 +64110,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63390,7 +64146,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -63449,7 +64205,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) { + else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || + (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -63458,7 +64215,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -63668,6 +64425,11 @@ var ts; write("["); } else { + if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { write("new "); @@ -63974,7 +64736,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } @@ -64158,7 +64920,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -64195,7 +64957,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -64283,7 +65045,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -64362,7 +65126,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -64580,7 +65344,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -64603,7 +65367,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions case 177 /* ArrayLiteralExpression */: @@ -64668,6 +65432,8 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* CommaListExpression */: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -64706,6 +65472,7 @@ var ts; // function emitIdentifier(node) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // // Names @@ -64734,6 +65501,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -64854,7 +65622,10 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65 /* TypeLiteralMembers */); + // If the literal is empty, do not add spaces between braces. + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); + } write("}"); } function emitArrayType(node) { @@ -64892,9 +65663,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -64905,8 +65682,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -64922,7 +65704,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); + emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); write("}"); } } @@ -65006,7 +65788,7 @@ var ts; // check if constant enum value is integer var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -65109,7 +65891,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -65837,6 +66619,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272 /* CommaListElements */); + } /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -66118,6 +66903,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -66300,7 +67094,9 @@ var ts; if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -66580,14 +67376,17 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -66814,6 +67613,90 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + // 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) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + 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. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -66863,6 +67746,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -66919,7 +67803,8 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); @@ -66978,7 +67863,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67016,76 +67902,100 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { - // if old program state is not supplied and file does not contain locally defined ambient modules - // then the best we can do is fallback to the default logic + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile); } - // at this point we know that either + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occured during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules - // OR // - old program state is available - // OR - // - both of items above - // With this it is possible that we can tell how some module names from the initial list will be resolved - // without doing actual resolution (in particular if some name was resolved to ambient module). - // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` - // since we don't want to resolve them again. - // this is a list of modules for which we cannot predict resolution so they should be actually resolved + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ var unknownModuleNames; - // this is a list of combined results assembles from predicted and resolved results. - // Order in this list matches the order in the original list of module names `moduleNames` which is important - // so later we can split results to resolutions of modules and resolutions of module augmentations. + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ var result; - // a transient placeholder that is used to mark predicted resolution in the result list + /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // module name is known to be resolved to ambient module if - // - module name is contained in the list of ambient modules that are locally declared in the file - // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // If we want to reuse resolutions more aggressively, we can refine this to check for whether the + // text of the corresponding modulenames has changed. + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file // (so the same module declaration will land in the new program) - var isKnownToResolveToAmbientModule = false; + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - // found a first module name for which result can be prediced - // this means that this module name should not be passed to `resolveModuleNamesWorker`. - // We'll use a separate list for module names that are definitely unknown. - result = new Array(moduleNames.length); - // copy all module names that appear before the current one in the list - // since they are known to be unknown - unknownModuleNames = moduleNames.slice(0, i); - } - // mark prediced resolution in the result list - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - // found unknown module name and we are already using separate list for those - add it to the list - unknownModuleNames.push(moduleName); + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - // we've looked throught the list but have not seen any predicted resolution - // use default logic - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; - // combine results of resolutions and predicted results + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -67094,16 +68004,15 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { // module used to be resolved to file - ignore it return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -67123,84 +68032,90 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0 /* Not */; } // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); // there is an old program, check if we can reuse its structure var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { + // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check tripleslash references if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - // file has no changes - use it as is - newSourceFile = oldSourceFile; - } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); // try to verify results of module resolution for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -67209,12 +68124,16 @@ var ts; // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { @@ -67227,8 +68146,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return { @@ -67616,7 +68534,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -67647,7 +68565,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -67694,7 +68611,7 @@ var ts; } break; case 233 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -67705,7 +68622,7 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -67734,45 +68651,52 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -67925,11 +68849,11 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -67986,7 +68910,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -68084,12 +69008,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -69266,57 +70190,37 @@ var ts; * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; + } + if (exclude) { + json.exclude = exclude; + } + if (files) { + json.files = files; + } + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; + } + return options; + })(); + options = ts.extend(existingOptions, options); + options.configFilePath = configFileName; // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } - options = ts.extend(existingOptions, options); - options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -69326,39 +70230,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -69389,9 +70261,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -69409,9 +70278,73 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, // Usually a string. + host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -70046,7 +70979,6 @@ var ts; case 148 /* PropertySignature */: case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: - case 264 /* EnumMember */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: case 152 /* Constructor */: @@ -70063,9 +70995,11 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 264 /* EnumMember */: case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; + case 232 /* EnumDeclaration */: + return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -70082,7 +71016,7 @@ var ts; case 238 /* ImportDeclaration */: case 243 /* ExportAssignment */: case 244 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; // An external module can be a Value case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; @@ -70241,7 +71175,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -70256,36 +71190,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -70623,45 +71527,25 @@ var ts; // exit early return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } // find the child that contains 'position' - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -70788,10 +71672,6 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; /** * returns true if the position is in between the open and close elements of an JSX expression. */ @@ -70830,13 +71710,27 @@ var ts; } ts.isInTemplateString = isInTemplateString; /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -70847,16 +71741,14 @@ var ts; // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + return kind === 2 /* SingleLineCommentTrivia */ || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === 47 /* slash */ && text.charCodeAt(end - 2) === 42 /* asterisk */); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); // First, we have to see if this position actually landed in a comment. @@ -70979,6 +71871,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -71027,25 +71922,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119 /* AnyKeyword */: @@ -71326,8 +72223,8 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; @@ -71422,7 +72319,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -71431,8 +72328,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72441,8 +73338,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -72733,7 +73630,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; @@ -72763,14 +73660,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -72826,8 +73725,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -72917,10 +73816,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -72948,9 +73848,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384 /* TypeParameter */) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -72958,16 +73859,20 @@ var ts; if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -73032,7 +73937,7 @@ var ts; log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); // Completion not allowed inside comments, bail out if this is the case - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -73083,7 +73988,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -73171,6 +74076,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -73204,7 +74110,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; @@ -73255,6 +74161,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -73264,6 +74171,11 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { @@ -73437,16 +74349,16 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { @@ -73469,7 +74381,11 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -73480,10 +74396,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -73525,6 +74437,53 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32 /* Static */) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -73561,6 +74520,44 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17 /* OpenBraceToken */: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number; | } + case 26 /* CommaToken */: + case 25 /* SemicolonToken */: + // class c { method() { } | } + case 18 /* CloseBraceToken */: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + // class c { method() { } | method2() { } } + if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -73673,7 +74670,7 @@ var ts; containingNodeKind === 231 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; + return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 146 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && @@ -73686,13 +74683,17 @@ var ts; return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || containingNodeKind === 240 /* NamespaceImport */; + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: case 89 /* FunctionKeyword */: case 104 /* VarKeyword */: - case 125 /* GetKeyword */: - case 135 /* SetKeyword */: case 91 /* ImportKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: @@ -73700,6 +74701,12 @@ var ts; case 138 /* TypeKeyword */: return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -73742,7 +74749,7 @@ var ts; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -73776,7 +74783,7 @@ var ts; continue; } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -73790,12 +74797,55 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 149 /* PropertyDeclaration */ && + m.kind !== 151 /* MethodDeclaration */ && + m.kind !== 153 /* GetAccessor */ && + m.kind !== 154 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + var mIsStatic = ts.hasModifier(m, 32 /* Static */); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8 /* Private */); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24 /* NonPublicAccessibilityModifier */); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * @@ -73807,7 +74857,7 @@ var ts; for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253 /* JsxAttribute */) { @@ -73816,6 +74866,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } /** * Get the name to be display in completion from a given symbol. @@ -73868,6 +74921,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 123 /* ConstructorKeyword */: + case 131 /* ReadonlyKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 120 /* AsyncKeyword */: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -73884,9 +74958,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -73898,8 +74972,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -74693,6 +75767,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74771,11 +75848,42 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -74799,7 +75907,7 @@ var ts; } /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -74827,26 +75935,20 @@ var ts; } } }); - if (sourceFile.flags & 65536 /* JavaScriptFile */) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 /* ImportDeclaration */ || decl.kind === 244 /* ExportDeclaration */) { - return decl; + switch (decl.kind) { + case 181 /* CallExpression */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return decl; + case 248 /* ExternalModuleReference */: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248 /* ExternalModuleReference */); - return decl.parent; } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. @@ -74983,12 +76085,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); - ts.Debug.assert(!!name); - return name; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { @@ -75035,12 +76138,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. @@ -75051,44 +76155,46 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -75098,10 +76204,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -75242,7 +76344,7 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265 /* SourceFile */) { return undefined; @@ -75253,6 +76355,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -75263,13 +76366,60 @@ var ts; // Can't have references to something that we have no symbol for. return undefined; } - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9 /* StringLiteral */) { + return false; + } + switch (node.parent.kind) { + case 233 /* ModuleDeclaration */: + case 248 /* ExternalModuleReference */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return true; + case 181 /* CallExpression */: + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265 /* 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 233 /* ModuleDeclaration */: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { @@ -75510,7 +76660,11 @@ var ts; // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. @@ -75542,16 +76696,12 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -75561,28 +76711,27 @@ var ts; // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case 71 /* Identifier */: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -75604,10 +76753,8 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } @@ -75738,7 +76885,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76004,9 +77151,9 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; var node = ts.getTouchingWord(sourceFile, position); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; @@ -76058,13 +77205,13 @@ var ts; if (searchSpaceNode.kind === 265 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -76110,10 +77257,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -76121,8 +77268,8 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; var node_7 = ts.getTouchingWord(sourceFile, position); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); @@ -76319,20 +77466,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -76501,17 +77648,10 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 71 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 242 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 241 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -76530,16 +77670,6 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -76550,16 +77680,10 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -76579,13 +77703,13 @@ var ts; return undefined; } if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -76593,6 +77717,28 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239 /* ImportClause */: + case 237 /* ImportEqualsDeclaration */: + return true; + case 242 /* ImportSpecifier */: + return declaration.parent.kind === 241 /* NamedImports */; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -76663,7 +77809,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -76691,7 +77837,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -76763,6 +77909,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -76773,8 +77920,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -77257,8 +78402,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. @@ -77301,17 +78446,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77340,8 +78488,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77379,6 +78528,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77388,8 +78538,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77641,8 +78791,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77731,9 +78881,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77750,7 +78900,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -79128,138 +80278,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -81588,9 +82633,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -81601,18 +82646,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -81620,51 +82661,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, + 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81689,6 +82759,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -81704,123 +82776,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true - // so if the option is undefined, we should treat it as true as well - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -82074,7 +83032,7 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -82171,7 +83129,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -83069,9 +84027,7 @@ var ts; if (node.kind === 20 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -83665,7 +84621,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); @@ -83694,27 +84650,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited @@ -83759,6 +84696,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -83827,14 +84774,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -83858,6 +84805,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -83924,7 +84916,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -84014,7 +85007,7 @@ var ts; /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); - var indexSignature = ts.createIndexSignatureDeclaration( + var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -84031,6 +85024,60 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 793064 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 107455 /* Value */; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84232,131 +85279,135 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - switch (token.parent.kind) { - case 226 /* VariableDeclaration */: - switch (token.parent.parent.parent.kind) { - case 214 /* ForStatement */: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216 /* ForOfStatement */: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return undefined; - case 260 /* CatchClause */: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - // TODO: #14885 - // falls through - case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); - case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); - } - else { - // delete import specifier - return deleteNodeInList(token.parent); - } - // handle case where "import d, * as ns from './file'" - // or "'import {a, b as ns} from './file'" - case 239 /* ImportClause */: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - // import |d,| * as ns from './file' - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226 /* VariableDeclaration */: + return deleteVariableDeclaration(token.parent); + case 145 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); + if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + // handle case where 'import a = A;' + case 237 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); + return deleteNode(importEquals); + case 242 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); + return deleteNode(importSpec); + } + else { + // delete import specifier + return deleteNodeInList(token.parent); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 239 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + // import |d,| * as ns from './file' + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + // token.parent is a variableDeclaration + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214 /* ForStatement */: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -84388,6 +85439,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -84485,400 +85545,393 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238 /* ImportDeclaration */) { + return node; } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + // insert after any existing imports + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + : isNamespaceImport + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - // if node_modules folder is in this folder or any of its parent folder, no need to keep it. - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -85010,7 +86063,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85068,7 +86121,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -85124,7 +86177,7 @@ var ts; /*returnType*/ undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration( + return ts.createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } @@ -85147,6 +86200,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -85156,6 +86210,188 @@ var ts; /// /// /// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 /* Function */ && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186 /* FunctionExpression */: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + case 187 /* ArrowFunction */: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 207 /* Block */) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + default: + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -85182,11 +86418,15 @@ var ts; /// /// /// +/// /// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; + /* @internal */ + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : @@ -85571,13 +86811,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -85962,7 +87203,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -85987,10 +87228,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - // Ensure rules are initialized and up to date wrt to formatting options - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -86283,7 +87520,7 @@ var ts; /// Goto implementation function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -86300,7 +87537,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -86333,11 +87570,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { @@ -86640,8 +87877,7 @@ var ts; var matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -86729,11 +87965,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -86859,20 +88119,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -88130,6 +89390,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -88304,3 +89567,5 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "2.4"; + +//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index f610c4fd273..4efda1e469e 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -25,12 +25,449 @@ var __extends = (this && this.__extends) || (function () { })(); var ts; (function (ts) { + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; + SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 126] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 127] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 128] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 129] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 130] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 131] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 132] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 133] = "NumberKeyword"; + SyntaxKind[SyntaxKind["ObjectKeyword"] = 134] = "ObjectKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 135] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 136] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; + SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; + SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; + SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; + SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; + SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 270] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 271] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 272] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 273] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 274] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 275] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 276] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 277] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 278] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 279] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 280] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 281] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 282] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 284] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 285] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 286] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 287] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 288] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 289] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 290] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 291] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 293] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 283] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; + (function (NodeFlags) { + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + var RelationComparisonResult; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + var GeneratedIdentifierKind; + (function (GeneratedIdentifierKind) { + GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; + })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var NumericLiteralFlags; + (function (NumericLiteralFlags) { + NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; + NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; + NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; + NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; + NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; + NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; + })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + var FlowFlags; + (function (FlowFlags) { + FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; + FlowFlags[FlowFlags["Start"] = 2] = "Start"; + FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; + FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; + FlowFlags[FlowFlags["Label"] = 12] = "Label"; + FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -40,13 +477,60 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + var TypeFormatFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 2] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 4] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 8] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 16] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 2048] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 4096] = "AddUndefined"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + var SymbolAccessibility; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -61,6 +545,196 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; + SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; + SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 16777216] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 33554432] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 67108864] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 134217728] = "Transient"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; + CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["Void"] = 1024] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 4096] = "Null"; + TypeFlags[TypeFlags["Never"] = 8192] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 32768] = "Object"; + TypeFlags[TypeFlags["Union"] = 65536] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 262144] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; + TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; + TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; + TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; + TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + var SignatureKind; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var SpecialPropertyAssignmentKind; + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -81,6 +755,179 @@ var ts; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + var DiagnosticStyle; + (function (DiagnosticStyle) { + DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; + DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; + })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var WatchDirectoryFlags; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { Extension[Extension["Ts"] = 0] = "Ts"; @@ -90,6 +937,126 @@ var ts; Extension[Extension["Jsx"] = 4] = "Jsx"; Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; })(Extension = ts.Extension || (ts.Extension = {})); + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; + ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; + ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + var EmitHint; + (function (EmitHint) { + EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; + EmitHint[EmitHint["Expression"] = 1] = "Expression"; + EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; + EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -155,6 +1122,12 @@ var ts; ts.version = "2.4.0"; })(ts || (ts = {})); (function (ts) { + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { @@ -288,6 +1261,12 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -325,6 +1304,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -529,6 +1517,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1553,6 +2563,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -1821,6 +2835,13 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + var ExtensionPriority; + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -1905,6 +2926,13 @@ var ts; getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } }; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -2224,6 +3252,11 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); function fileSystemEntryExists(path, entryKind) { try { var stat = _fs.statSync(path); @@ -2589,6 +3622,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2696,7 +3730,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -2891,6 +3925,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3186,6 +4228,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -3231,6 +4274,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3312,6 +4357,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -3860,9 +4908,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -5873,49 +6922,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -5925,37 +6953,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -5986,9 +6984,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -6005,9 +7000,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -6455,12 +7507,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -6744,6 +7795,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -6877,12 +7930,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -6912,7 +7971,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -7646,6 +8704,9 @@ var ts; _this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package..."); } _this.execSync(_this.npmPath + " install " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + if (_this.log.isEnabled()) { + _this.log.writeLine("Updated " + TypesRegistryPackageName + " npm package"); + } } catch (e) { if (_this.log.isEnabled()) { @@ -7729,3 +8790,5 @@ var ts; })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); + +//# sourceMappingURL=typingsInstaller.js.map diff --git a/src/server/client.ts b/src/server/client.ts index e29261f7244..aca52422e44 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -224,7 +224,7 @@ namespace ts.server { return { name, kind, kindModifiers, sortText, replacementSpan: convertedSpan }; } - return entry as { name: string, kind: string, kindModifiers: string, sortText: string }; + return entry as { name: string, kind: ScriptElementKind, kindModifiers: string, sortText: string }; }) }; } @@ -265,7 +265,7 @@ namespace ts.server { return { name: entry.name, containerName: entry.containerName || "", - containerKind: entry.containerKind || "", + containerKind: entry.containerKind || ScriptElementKind.unknown, kind: entry.kind, kindModifiers: entry.kindModifiers, matchKind: entry.matchKind, @@ -330,11 +330,11 @@ namespace ts.server { const start = this.lineOffsetToPosition(fileName, entry.start); const end = this.lineOffsetToPosition(fileName, entry.end); return { - containerKind: "", + containerKind: ScriptElementKind.unknown, containerName: "", fileName: fileName, textSpan: ts.createTextSpanFromBounds(start, end), - kind: "", + kind: ScriptElementKind.unknown, name: "" }; }); @@ -356,11 +356,11 @@ namespace ts.server { const start = this.lineOffsetToPosition(fileName, entry.start); const end = this.lineOffsetToPosition(fileName, entry.end); return { - containerKind: "", + containerKind: ScriptElementKind.unknown, containerName: "", fileName: fileName, textSpan: ts.createTextSpanFromBounds(start, end), - kind: "", + kind: ScriptElementKind.unknown, name: "" }; }); diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 8d85ad125d5..de124714d68 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -698,10 +698,9 @@ namespace ts.server.protocol { /** * Span augmented with extra information that denotes the kind of the highlighting to be used for span. - * Kind is taken from HighlightSpanKind type. */ export interface HighlightSpan extends TextSpan { - kind: string; + kind: HighlightSpanKind; } /** @@ -838,7 +837,7 @@ namespace ts.server.protocol { /** * The items's kind (such as 'className' or 'parameterName' or plain 'text'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). @@ -1352,7 +1351,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). @@ -1571,7 +1570,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). */ @@ -1599,7 +1598,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). */ @@ -2058,7 +2057,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * exact, substring, or prefix. @@ -2099,7 +2098,7 @@ namespace ts.server.protocol { /** * Kind of symbol's container symbol (if any). */ - containerKind?: string; + containerKind?: ScriptElementKind; } /** @@ -2172,7 +2171,7 @@ namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * Optional modifiers for the kind (such as 'public'). @@ -2198,7 +2197,7 @@ namespace ts.server.protocol { /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ export interface NavigationTree { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems?: NavigationTree[]; diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 9580d679fba..42945cb592c 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -145,7 +145,7 @@ namespace ts.FindAllReferences { const { node, name, kind, displayParts } = info; const sourceFile = node.getSourceFile(); return { - containerKind: "", + containerKind: ScriptElementKind.unknown, containerName: "", fileName: sourceFile.fileName, kind, @@ -155,7 +155,7 @@ namespace ts.FindAllReferences { }; } - function getDefinitionKindAndDisplayParts(symbol: Symbol, node: Node, checker: TypeChecker): { displayParts: SymbolDisplayPart[], kind: string } { + function getDefinitionKindAndDisplayParts(symbol: Symbol, node: Node, checker: TypeChecker): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } { const { displayParts, symbolKind } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), getContainerNode(node), node); return { displayParts, kind: symbolKind }; @@ -186,7 +186,7 @@ namespace ts.FindAllReferences { } } - function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: string, displayParts: SymbolDisplayPart[] } { + function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: ScriptElementKind, displayParts: SymbolDisplayPart[] } { const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node); if (symbol) { return getDefinitionKindAndDisplayParts(symbol, node, checker); diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 47a57e4d101..672b484055f 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -165,7 +165,7 @@ namespace ts.GoToDefinition { return result; - function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) { + function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) { // 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 (isNewExpressionTarget(location) || location.kind === SyntaxKind.ConstructorKeyword) { @@ -173,12 +173,8 @@ namespace ts.GoToDefinition { // Find the first class-like declaration and try to get the construct signature. for (const declaration of symbol.getDeclarations()) { if (isClassLike(declaration)) { - return tryAddSignature(declaration.members, - /*selectConstructors*/ true, - symbolKind, - symbolName, - containerName, - result); + return tryAddSignature( + declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); } } @@ -188,14 +184,14 @@ namespace ts.GoToDefinition { return false; } - function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) { + function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) { if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); } return false; } - function tryAddSignature(signatureDeclarations: Declaration[] | undefined, selectConstructors: boolean, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) { + function tryAddSignature(signatureDeclarations: Declaration[] | undefined, selectConstructors: boolean, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) { if (!signatureDeclarations) { return false; } @@ -231,12 +227,12 @@ namespace ts.GoToDefinition { } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ - function createDefinitionInfo(node: Declaration, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo { + function createDefinitionInfo(node: Declaration, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo { return createDefinitionInfoFromName(getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ - function createDefinitionInfoFromName(name: Node, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo { + function createDefinitionInfoFromName(name: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo { const sourceFile = name.getSourceFile(); return { fileName: sourceFile.fileName, diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 2fdc567b9bb..d4adeaea974 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -205,7 +205,7 @@ namespace ts.NavigateTo { textSpan: createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? (containerName).text : "", - containerKind: containerName ? getNodeKind(container) : "" + containerKind: containerName ? getNodeKind(container) : ScriptElementKind.unknown }; } } diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 2b45457c147..f68c8276254 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -458,7 +458,7 @@ namespace ts.Completions.PathCompletions { } } - function createCompletionEntryForModule(name: string, kind: string, replacementSpan: TextSpan): CompletionEntry { + function createCompletionEntryForModule(name: string, kind: ScriptElementKind, replacementSpan: TextSpan): CompletionEntry { return { name, kind, kindModifiers: ScriptElementKindModifier.none, sortText: name, replacementSpan }; } diff --git a/src/services/rename.ts b/src/services/rename.ts index 27c47179052..6091c0b2d03 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -53,7 +53,7 @@ namespace ts.Rename { } } - function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { + function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { return { canRename: true, kind, diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 67bacaeadd0..910c31c36b3 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -1,7 +1,7 @@ /* @internal */ namespace ts.SymbolDisplay { // TODO(drosen): use contextual SemanticMeaning. - export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): string { + export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind { const { flags } = symbol; if (flags & SymbolFlags.Class) return getDeclarationOfKind(symbol, SyntaxKind.ClassExpression) ? @@ -22,7 +22,7 @@ namespace ts.SymbolDisplay { return result; } - function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker: TypeChecker, symbol: Symbol, location: Node) { + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind { if (typeChecker.isUndefinedSymbol(symbol)) { return ScriptElementKind.variableElement; } diff --git a/src/services/types.ts b/src/services/types.ts index 6c64ce5b9ba..6f0b3baf532 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -297,7 +297,7 @@ namespace ts { */ export interface NavigationBarItem { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems: NavigationBarItem[]; @@ -313,8 +313,7 @@ namespace ts { export interface NavigationTree { /** Name of the declaration, or a short description, e.g. "". */ text: string; - /** A ScriptElementKind */ - kind: string; + kind: ScriptElementKind; /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ kindModifiers: string; /** @@ -380,7 +379,7 @@ namespace ts { } export interface ImplementationLocation extends DocumentSpan { - kind: string; + kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; } @@ -389,30 +388,30 @@ namespace ts { highlightSpans: HighlightSpan[]; } - export namespace HighlightSpanKind { - export const none = "none"; - export const definition = "definition"; - export const reference = "reference"; - export const writtenReference = "writtenReference"; + export const enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference", } export interface HighlightSpan { fileName?: string; isInString?: true; textSpan: TextSpan; - kind: string; + kind: HighlightSpanKind; } export interface NavigateToItem { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; - matchKind: string; + matchKind: string; // TODO: keyof typeof PatternMatchKind; (https://github.com/Microsoft/TypeScript/issues/15102) isCaseSensitive: boolean; fileName: string; textSpan: TextSpan; containerName: string; - containerKind: string; + containerKind: ScriptElementKind; } export enum IndentStyle { @@ -480,9 +479,9 @@ namespace ts { export interface DefinitionInfo { fileName: string; textSpan: TextSpan; - kind: string; + kind: ScriptElementKind; name: string; - containerKind: string; + containerKind: ScriptElementKind; containerName: string; } @@ -522,7 +521,7 @@ namespace ts { export interface SymbolDisplayPart { text: string; - kind: string; // A ScriptElementKind + kind: string; } export interface JSDocTagInfo { @@ -531,7 +530,7 @@ namespace ts { } export interface QuickInfo { - kind: string; + kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; @@ -544,7 +543,7 @@ namespace ts { localizedErrorMessage: string; displayName: string; fullDisplayName: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } @@ -597,7 +596,7 @@ namespace ts { export interface CompletionEntry { name: string; - kind: string; // see ScriptElementKind + kind: ScriptElementKind; kindModifiers: string; // see ScriptElementKindModifier, comma separated sortText: string; /** @@ -610,7 +609,7 @@ namespace ts { export interface CompletionEntryDetails { name: string; - kind: string; // see ScriptElementKind + kind: ScriptElementKind; kindModifiers: string; // see ScriptElementKindModifier, comma separated displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; @@ -708,102 +707,101 @@ namespace ts { getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } - // TODO: move these to enums - export namespace ScriptElementKind { - export const unknown = ""; - export const warning = "warning"; + export const enum ScriptElementKind { + unknown = "", + warning = "warning", /** predefined type (void) or keyword (class) */ - export const keyword = "keyword"; + keyword = "keyword", /** top level script node */ - export const scriptElement = "script"; + scriptElement = "script", /** module foo {} */ - export const moduleElement = "module"; + moduleElement = "module", /** class X {} */ - export const classElement = "class"; + classElement = "class", /** var x = class X {} */ - export const localClassElement = "local class"; + localClassElement = "local class", /** interface Y {} */ - export const interfaceElement = "interface"; + interfaceElement = "interface", /** type T = ... */ - export const typeElement = "type"; + typeElement = "type", /** enum E */ - export const enumElement = "enum"; - export const enumMemberElement = "enum member"; + enumElement = "enum", + enumMemberElement = "enum member", /** * Inside module and script only * const v = .. */ - export const variableElement = "var"; + variableElement = "var", /** Inside function */ - export const localVariableElement = "local var"; + localVariableElement = "local var", /** * Inside module and script only * function f() { } */ - export const functionElement = "function"; + functionElement = "function", /** Inside function */ - export const localFunctionElement = "local function"; + localFunctionElement = "local function", /** class X { [public|private]* foo() {} } */ - export const memberFunctionElement = "method"; + memberFunctionElement = "method", /** class X { [public|private]* [get|set] foo:number; } */ - export const memberGetAccessorElement = "getter"; - export const memberSetAccessorElement = "setter"; + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", /** * class X { [public|private]* foo:number; } * interface Y { foo:number; } */ - export const memberVariableElement = "property"; + memberVariableElement = "property", /** class X { constructor() { } } */ - export const constructorImplementationElement = "constructor"; + constructorImplementationElement = "constructor", /** interface Y { ():number; } */ - export const callSignatureElement = "call"; + callSignatureElement = "call", /** interface Y { []:number; } */ - export const indexSignatureElement = "index"; + indexSignatureElement = "index", /** interface Y { new():Y; } */ - export const constructSignatureElement = "construct"; + constructSignatureElement = "construct", /** function foo(*Y*: string) */ - export const parameterElement = "parameter"; + parameterElement = "parameter", - export const typeParameterElement = "type parameter"; + typeParameterElement = "type parameter", - export const primitiveType = "primitive type"; + primitiveType = "primitive type", - export const label = "label"; + label = "label", - export const alias = "alias"; + alias = "alias", - export const constElement = "const"; + constElement = "const", - export const letElement = "let"; + letElement = "let", - export const directory = "directory"; + directory = "directory", - export const externalModuleName = "external module name"; + externalModuleName = "external module name", /** * */ - export const jsxAttribute = "JSX attribute"; + jsxAttribute = "JSX attribute", } export namespace ScriptElementKindModifier { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 0555ed93c3f..4a3f8769b61 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -279,7 +279,7 @@ namespace ts { } } - export function getNodeKind(node: Node): string { + export function getNodeKind(node: Node): ScriptElementKind { switch (node.kind) { case SyntaxKind.SourceFile: return isExternalModule(node) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement; @@ -326,7 +326,7 @@ namespace ts { return ScriptElementKind.unknown; } - function getKindOfVariableDeclaration(v: VariableDeclaration): string { + function getKindOfVariableDeclaration(v: VariableDeclaration): ScriptElementKind { return isConst(v) ? ScriptElementKind.constElement : isLet(v) From 2068192e5b738626009acd481766d5994214c794 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sun, 21 May 2017 04:33:33 +1000 Subject: [PATCH 251/282] export type used by an exported function (#15965) --- src/services/importTracker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 4fd9fed346d..f20c80c14ef 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -300,7 +300,7 @@ namespace ts.FindAllReferences { }); } - type ModuleReference = + export type ModuleReference = /** "import" also includes require() calls. */ | { kind: "import", literal: StringLiteral } /** or */ From 694efba7d2e7af34cf06b416bcea319ea8cf4b91 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 22 May 2017 07:48:40 -0700 Subject: [PATCH 252/282] Fix use of getTokenAtPosition to use updated signature --- src/services/refactors/convertFunctionToEs6Class.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/services/refactors/convertFunctionToEs6Class.ts b/src/services/refactors/convertFunctionToEs6Class.ts index 3f1a359c7a1..a34e0ccca2f 100644 --- a/src/services/refactors/convertFunctionToEs6Class.ts +++ b/src/services/refactors/convertFunctionToEs6Class.ts @@ -12,7 +12,7 @@ namespace ts.refactor { function isApplicable(context: RefactorContext): boolean { const start = context.startPosition; - const node = getTokenAtPosition(context.file, start); + const node = getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); const checker = context.program.getTypeChecker(); let symbol = checker.getSymbolAtLocation(node); @@ -27,7 +27,7 @@ namespace ts.refactor { const start = context.startPosition; const sourceFile = context.file; const checker = context.program.getTypeChecker(); - const token = getTokenAtPosition(sourceFile, start); + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); const ctorSymbol = checker.getSymbolAtLocation(token); const newLine = context.rulesProvider.getFormatOptions().newLineCharacter; From fea8561d1b69311e70a396f3b62d41af0583239c Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 22 May 2017 10:06:35 -0700 Subject: [PATCH 253/282] Remove dead code from binder `getNameOfDeclaration` now handles a lot of the special property assignment kinds in `getDeclarationName` --- src/compiler/binder.ts | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 1940231a6d1..9bdc85ef6ba 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -260,18 +260,9 @@ namespace ts { case SyntaxKind.ExportAssignment: return (node).isExportEquals ? "export=" : "default"; case SyntaxKind.BinaryExpression: - switch (getSpecialPropertyAssignmentKind(node as BinaryExpression)) { - case SpecialPropertyAssignmentKind.ModuleExports: - // module.exports = ... - return "export="; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - // exports.x = ... or this.y = ... - return ((node as BinaryExpression).left as PropertyAccessExpression).name.text; - case SpecialPropertyAssignmentKind.PrototypeProperty: - // className.prototype.methodName = ... - return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text; + if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) { + // module.exports = ... + return "export="; } Debug.fail("Unknown binary declaration kind"); break; From a0fa8ae6c4a19cc893f44036177c18c553b2070d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 22 May 2017 10:18:31 -0700 Subject: [PATCH 254/282] Address most PR comments I am still working on the error for class expressions that extend from a non-exported base. --- src/compiler/checker.ts | 19 +++++++++--- src/compiler/declarationEmitter.ts | 16 ++++++++-- src/compiler/types.ts | 29 ++++++++++--------- .../emitClassExpressionInDeclarationFile.ts | 7 +++++ ...findAllRefsForVariableInExtendsClause01.ts | 2 +- tests/cases/fourslash/renameJsExports02.ts | 4 +-- 6 files changed, 53 insertions(+), 24 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d10a07ad6b7..cae9f2dac25 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3154,7 +3154,7 @@ namespace ts { } function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) { - const globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; + const globalFlagsToPass = globalFlags & (TypeFormatFlags.WriteOwnNameForAnyLike | TypeFormatFlags.WriteClassExpressionAsTypeLiteral); let inObjectTypeLiteral = false; return writeType(type, globalFlags); @@ -3266,7 +3266,9 @@ namespace ts { writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), SyntaxKind.CommaToken); writePunctuation(writer, SyntaxKind.CloseBracketToken); } - else if (type.symbol.valueDeclaration && type.symbol.valueDeclaration.kind === SyntaxKind.ClassExpression) { + else if (flags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === SyntaxKind.ClassExpression) { writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); } else { @@ -3316,7 +3318,9 @@ namespace ts { const symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) && symbol.valueDeclaration.kind !== SyntaxKind.ClassExpression || + if (symbol.flags & SymbolFlags.Class && + !getBaseTypeVariableOfClass(symbol) && + !(symbol.valueDeclaration.kind === SyntaxKind.ClassExpression && flags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral) || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule)) { writeTypeOfSymbol(type, flags); } @@ -3348,6 +3352,8 @@ namespace ts { getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class; if (isConstructorObject) { + // TODO: something needs to issue accessibility errors (here, I think) + // before writing a literal type that flattens base types, check that the base types are accessible writeLiteralType(type, flags); } else { @@ -3473,6 +3479,11 @@ namespace ts { buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, IndexKind.String, enclosingDeclaration, globalFlags, symbolStack); buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, IndexKind.Number, enclosingDeclaration, globalFlags, symbolStack); for (const p of resolved.properties) { + if (globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral && + (p.name === "prototype" || + getDeclarationModifierFlagsFromSymbol(p) & (ModifierFlags.Private | ModifierFlags.Protected))) { + continue; + } const t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { const signatures = getSignaturesOfType(t, SignatureKind.Call); @@ -3487,7 +3498,7 @@ namespace ts { writePropertyWithModifiers(p); writePunctuation(writer, SyntaxKind.ColonToken); writeSpace(writer); - writeType(t, TypeFormatFlags.None); + writeType(t, globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 4d06b41f377..89358872a0f 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -344,7 +344,9 @@ namespace ts { } else { errorNameNode = declaration.name; - const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | + const format = TypeFormatFlags.UseTypeOfFunction | + TypeFormatFlags.WriteClassExpressionAsTypeLiteral | + TypeFormatFlags.UseTypeAliasValue | (shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; @@ -360,7 +362,11 @@ namespace ts { } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); + resolver.writeReturnTypeOfSignatureDeclaration( + signature, + enclosingDeclaration, + TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral, + writer); errorNameNode = undefined; } } @@ -621,7 +627,11 @@ namespace ts { write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = () => diagnostic; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); + resolver.writeTypeOfExpression( + expr, + enclosingDeclaration, + TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral, + writer); write(";"); writeLine(); return tempVarName; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 0283c45f2e1..069f8b967cf 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2652,20 +2652,21 @@ namespace ts { } export const enum TypeFormatFlags { - None = 0x00000000, - WriteArrayAsGenericType = 0x00000001, // Write Array instead T[] - UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal - NoTruncation = 0x00000004, // Don't truncate typeToString result - WriteArrowStyleSignature = 0x00000008, // Write arrow style signature - WriteOwnNameForAnyLike = 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) - WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature - InElementType = 0x00000040, // Writing an array or union element type - UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type) - InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type - InTypeAlias = 0x00000200, // Writing type in type alias declaration - UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. - SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type. - AddUndefined = 0x00001000, // Add undefined to types of initialized, non-optional parameters + None = 0, + WriteArrayAsGenericType = 1 << 0, // Write Array instead T[] + UseTypeOfFunction = 1 << 2, // Write typeof instead of function type literal + NoTruncation = 1 << 3, // Don't truncate typeToString result + WriteArrowStyleSignature = 1 << 4, // Write arrow style signature + WriteOwnNameForAnyLike = 1 << 5, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) + WriteTypeArgumentsOfSignature = 1 << 6, // Write the type arguments instead of type parameters of the signature + InElementType = 1 << 7, // Writing an array or union element type + UseFullyQualifiedType = 1 << 8, // Write out the fully qualified type name (eg. Module.Type, instead of Type) + InFirstTypeArgument = 1 << 9, // Writing first type argument of the instantiated type + InTypeAlias = 1 << 10, // Writing type in type alias declaration + UseTypeAliasValue = 1 << 11, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. + SuppressAnyReturnType = 1 << 12, // If the return type is any-like, don't offer a return type. + AddUndefined = 1 << 13, // Add undefined to types of initialized, non-optional parameters + WriteClassExpressionAsTypeLiteral = 1 << 14, // Write a type literal instead of (Anonymous class) } export const enum SymbolFormatFlags { diff --git a/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts index f99bcbd7efd..4268f237044 100644 --- a/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts +++ b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts @@ -2,12 +2,19 @@ export var simpleExample = class { static getTags() { } tags() { } + private static ps = -1 + private p = 12 } export var circularReference = class C { static getTags(c: C): C { return c } tags(c: C): C { return c } } +class Base { } +export function foo() { + return class extends Base { } +} + // repro from #15066 export class FooItem { foo(): void { } diff --git a/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts b/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts index 9d79d97d419..a61f925c97e 100644 --- a/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts +++ b/tests/cases/fourslash/findAllRefsForVariableInExtendsClause01.ts @@ -3,4 +3,4 @@ ////var [|{| "isWriteAccess": true, "isDefinition": true |}Base|] = class { }; ////class C extends [|Base|] { } -verify.singleReferenceGroup("var Base: {\n new (): {};\n prototype: {};\n}"); +verify.singleReferenceGroup("var Base: typeof Base"); diff --git a/tests/cases/fourslash/renameJsExports02.ts b/tests/cases/fourslash/renameJsExports02.ts index ef39bbc83b6..94c84980784 100644 --- a/tests/cases/fourslash/renameJsExports02.ts +++ b/tests/cases/fourslash/renameJsExports02.ts @@ -10,7 +10,7 @@ const [r0, r1] = test.ranges(); verify.referenceGroups(r0, [ { definition: "(local class) A", ranges: [r0] }, - { definition: "const A: {\n new (): {};\n prototype: {};\n}", ranges: [r1] } + { definition: "const A: typeof A", ranges: [r1] } ]); -verify.singleReferenceGroup("const A: {\n new (): {};\n prototype: {};\n}", [r1]); +verify.singleReferenceGroup("const A: typeof A", [r1]); From bba8e744966177e1ccfae0b32bd02ad9efd941f0 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 22 May 2017 10:25:40 -0700 Subject: [PATCH 255/282] Fix path in importDeclTypes.ts test (#15992) --- tests/baselines/reference/importDeclTypes.errors.txt | 4 ++-- tests/cases/compiler/importDeclTypes.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/baselines/reference/importDeclTypes.errors.txt b/tests/baselines/reference/importDeclTypes.errors.txt index dfb8fcb6f48..ee2a9c86eb5 100644 --- a/tests/baselines/reference/importDeclTypes.errors.txt +++ b/tests/baselines/reference/importDeclTypes.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.ts(1,21): error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'. +/a.ts(1,21): error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'. ==== /node_modules/@types/foo-bar/index.d.ts (0 errors) ==== @@ -7,7 +7,7 @@ tests/cases/compiler/a.ts(1,21): error TS6137: Cannot import type declaration fi } // This should error -==== tests/cases/compiler/a.ts (1 errors) ==== +==== /a.ts (1 errors) ==== import { Foo } from "@types/foo-bar"; ~~~~~~~~~~~~~~~~ !!! error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'. diff --git a/tests/cases/compiler/importDeclTypes.ts b/tests/cases/compiler/importDeclTypes.ts index 01fcd0e7b6f..ab7ba50c236 100644 --- a/tests/cases/compiler/importDeclTypes.ts +++ b/tests/cases/compiler/importDeclTypes.ts @@ -5,5 +5,5 @@ export interface Foo { } // This should error -// @filename: a.ts +// @filename: /a.ts import { Foo } from "@types/foo-bar"; From f94818da36c58f9fc0d6d535677f6500a096f6de Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 22 May 2017 10:40:59 -0700 Subject: [PATCH 256/282] Also convert ClassificationTypeNames and CommandTypes/CommandNames --- src/harness/fourslash.ts | 105 ++++++++++++++------------- src/server/protocol.ts | 144 ++++++++++++++++++------------------- src/server/session.ts | 99 +------------------------ src/services/classifier.ts | 2 +- src/services/types.ts | 68 +++++++++--------- 5 files changed, 163 insertions(+), 255 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index fc50e71478e..7e2387ed636 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2174,7 +2174,7 @@ namespace FourSlash { } ts.zipWith(expected, actual, (expectedClassification, actualClassification) => { - const expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; + const expectedType = expectedClassification.classificationType; if (expectedType !== actualClassification.classificationType) { this.raiseError("verifyClassifications failed - expected classifications type to be " + expectedType + ", but was " + @@ -3876,7 +3876,7 @@ namespace FourSlashInterface { /** * This method *requires* an ordered stream of classifications for a file, and spans are highly recommended. */ - public semanticClassificationsAre(...classifications: { classificationType: string; text: string; textSpan?: FourSlash.TextSpan }[]) { + public semanticClassificationsAre(...classifications: Classification[]) { this.state.verifySemanticClassifications(classifications); } @@ -4071,102 +4071,107 @@ namespace FourSlashInterface { } } + interface Classification { + classificationType: ts.ClassificationTypeNames; + text: string; + textSpan?: FourSlash.TextSpan; + } export namespace Classification { - export function comment(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("comment", text, position); + export function comment(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.comment, text, position); } - export function identifier(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("identifier", text, position); + export function identifier(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.identifier, text, position); } - export function keyword(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("keyword", text, position); + export function keyword(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.keyword, text, position); } - export function numericLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("numericLiteral", text, position); + export function numericLiteral(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.numericLiteral, text, position); } - export function operator(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("operator", text, position); + export function operator(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.operator, text, position); } - export function stringLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("stringLiteral", text, position); + export function stringLiteral(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.stringLiteral, text, position); } - export function whiteSpace(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("whiteSpace", text, position); + export function whiteSpace(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.whiteSpace, text, position); } - export function text(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("text", text, position); + export function text(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.text, text, position); } - export function punctuation(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("punctuation", text, position); + export function punctuation(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.punctuation, text, position); } - export function docCommentTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("docCommentTagName", text, position); + export function docCommentTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.docCommentTagName, text, position); } - export function className(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("className", text, position); + export function className(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.className, text, position); } - export function enumName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("enumName", text, position); + export function enumName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.enumName, text, position); } - export function interfaceName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("interfaceName", text, position); + export function interfaceName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.interfaceName, text, position); } - export function moduleName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("moduleName", text, position); + export function moduleName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.moduleName, text, position); } - export function typeParameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("typeParameterName", text, position); + export function typeParameterName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.typeParameterName, text, position); } - export function parameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("parameterName", text, position); + export function parameterName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.parameterName, text, position); } - export function typeAliasName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("typeAliasName", text, position); + export function typeAliasName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.typeAliasName, text, position); } - export function jsxOpenTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxOpenTagName", text, position); + export function jsxOpenTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxOpenTagName, text, position); } - export function jsxCloseTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxCloseTagName", text, position); + export function jsxCloseTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxCloseTagName, text, position); } - export function jsxSelfClosingTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxSelfClosingTagName", text, position); + export function jsxSelfClosingTagName(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxSelfClosingTagName, text, position); } - export function jsxAttribute(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxAttribute", text, position); + export function jsxAttribute(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxAttribute, text, position); } - export function jsxText(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxText", text, position); + export function jsxText(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxText, text, position); } - export function jsxAttributeStringLiteralValue(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } { - return getClassification("jsxAttributeStringLiteralValue", text, position); + export function jsxAttributeStringLiteralValue(text: string, position?: number): Classification { + return getClassification(ts.ClassificationTypeNames.jsxAttributeStringLiteralValue, text, position); } - function getClassification(type: string, text: string, position?: number) { + function getClassification(classificationType: ts.ClassificationTypeNames, text: string, position?: number): Classification { return { - classificationType: type, + classificationType, text: text, textSpan: position === undefined ? undefined : { start: position, end: position + text.length } }; diff --git a/src/server/protocol.ts b/src/server/protocol.ts index de124714d68..c51743e1c39 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2,103 +2,103 @@ * Declaration module describing the TypeScript Server protocol */ namespace ts.server.protocol { - export namespace CommandTypes { - export type Brace = "brace"; + export enum CommandTypes { + Brace = "brace", /* @internal */ - export type BraceFull = "brace-full"; - export type BraceCompletion = "braceCompletion"; - export type Change = "change"; - export type Close = "close"; - export type Completions = "completions"; + BraceFull = "brace-full", + BraceCompletion = "braceCompletion", + Change = "change", + Close = "close", + Completions = "completions", /* @internal */ - export type CompletionsFull = "completions-full"; - export type CompletionDetails = "completionEntryDetails"; - export type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - export type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - export type Configure = "configure"; - export type Definition = "definition"; + CompletionsFull = "completions-full", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", /* @internal */ - export type DefinitionFull = "definition-full"; - export type Implementation = "implementation"; + DefinitionFull = "definition-full", + Implementation = "implementation", /* @internal */ - export type ImplementationFull = "implementation-full"; - export type Exit = "exit"; - export type Format = "format"; - export type Formatonkey = "formatonkey"; + ImplementationFull = "implementation-full", + Exit = "exit", + Format = "format", + Formatonkey = "formatonkey", /* @internal */ - export type FormatFull = "format-full"; + FormatFull = "format-full", /* @internal */ - export type FormatonkeyFull = "formatonkey-full"; + FormatonkeyFull = "formatonkey-full", /* @internal */ - export type FormatRangeFull = "formatRange-full"; - export type Geterr = "geterr"; - export type GeterrForProject = "geterrForProject"; - export type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - export type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - export type NavBar = "navbar"; + FormatRangeFull = "formatRange-full", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + NavBar = "navbar", /* @internal */ - export type NavBarFull = "navbar-full"; - export type Navto = "navto"; + NavBarFull = "navbar-full", + Navto = "navto", /* @internal */ - export type NavtoFull = "navto-full"; - export type NavTree = "navtree"; - export type NavTreeFull = "navtree-full"; - export type Occurrences = "occurrences"; - export type DocumentHighlights = "documentHighlights"; + NavtoFull = "navto-full", + NavTree = "navtree", + NavTreeFull = "navtree-full", + Occurrences = "occurrences", + DocumentHighlights = "documentHighlights", /* @internal */ - export type DocumentHighlightsFull = "documentHighlights-full"; - export type Open = "open"; - export type Quickinfo = "quickinfo"; + DocumentHighlightsFull = "documentHighlights-full", + Open = "open", + Quickinfo = "quickinfo", /* @internal */ - export type QuickinfoFull = "quickinfo-full"; - export type References = "references"; + QuickinfoFull = "quickinfo-full", + References = "references", /* @internal */ - export type ReferencesFull = "references-full"; - export type Reload = "reload"; - export type Rename = "rename"; + ReferencesFull = "references-full", + Reload = "reload", + Rename = "rename", /* @internal */ - export type RenameInfoFull = "rename-full"; + RenameInfoFull = "rename-full", /* @internal */ - export type RenameLocationsFull = "renameLocations-full"; - export type Saveto = "saveto"; - export type SignatureHelp = "signatureHelp"; + RenameLocationsFull = "renameLocations-full", + Saveto = "saveto", + SignatureHelp = "signatureHelp", /* @internal */ - export type SignatureHelpFull = "signatureHelp-full"; - export type TypeDefinition = "typeDefinition"; - export type ProjectInfo = "projectInfo"; - export type ReloadProjects = "reloadProjects"; - export type Unknown = "unknown"; - export type OpenExternalProject = "openExternalProject"; - export type OpenExternalProjects = "openExternalProjects"; - export type CloseExternalProject = "closeExternalProject"; + SignatureHelpFull = "signatureHelp-full", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", /* @internal */ - export type SynchronizeProjectList = "synchronizeProjectList"; + SynchronizeProjectList = "synchronizeProjectList", /* @internal */ - export type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + ApplyChangedToOpenFiles = "applyChangedToOpenFiles", /* @internal */ - export type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full", /* @internal */ - export type Cleanup = "cleanup"; + Cleanup = "cleanup", /* @internal */ - export type OutliningSpans = "outliningSpans"; - export type TodoComments = "todoComments"; - export type Indentation = "indentation"; - export type DocCommentTemplate = "docCommentTemplate"; + OutliningSpans = "outliningSpans", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", /* @internal */ - export type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full", /* @internal */ - export type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + NameOrDottedNameSpan = "nameOrDottedNameSpan", /* @internal */ - export type BreakpointStatement = "breakpointStatement"; - export type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - export type GetCodeFixes = "getCodeFixes"; + BreakpointStatement = "breakpointStatement", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", /* @internal */ - export type GetCodeFixesFull = "getCodeFixes-full"; - export type GetSupportedCodeFixes = "getSupportedCodeFixes"; + GetCodeFixesFull = "getCodeFixes-full", + GetSupportedCodeFixes = "getSupportedCodeFixes", - export type GetApplicableRefactors = "getApplicableRefactors"; - export type GetRefactorCodeActions = "getRefactorCodeActions"; - export type GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; + GetApplicableRefactors = "getApplicableRefactors", + GetRefactorCodeActions = "getRefactorCodeActions", + GetRefactorCodeActionsFull = "getRefactorCodeActions-full", } /** diff --git a/src/server/session.ts b/src/server/session.ts index bae53dcafe8..846607cd5ca 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -112,104 +112,7 @@ namespace ts.server { return true; } - export namespace CommandNames { - export const Brace: protocol.CommandTypes.Brace = "brace"; - /* @internal */ - export const BraceFull: protocol.CommandTypes.BraceFull = "brace-full"; - export const BraceCompletion: protocol.CommandTypes.BraceCompletion = "braceCompletion"; - export const Change: protocol.CommandTypes.Change = "change"; - export const Close: protocol.CommandTypes.Close = "close"; - export const Completions: protocol.CommandTypes.Completions = "completions"; - /* @internal */ - export const CompletionsFull: protocol.CommandTypes.CompletionsFull = "completions-full"; - export const CompletionDetails: protocol.CommandTypes.CompletionDetails = "completionEntryDetails"; - export const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - export const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - export const Configure: protocol.CommandTypes.Configure = "configure"; - export const Definition: protocol.CommandTypes.Definition = "definition"; - /* @internal */ - export const DefinitionFull: protocol.CommandTypes.DefinitionFull = "definition-full"; - export const Exit: protocol.CommandTypes.Exit = "exit"; - export const Format: protocol.CommandTypes.Format = "format"; - export const Formatonkey: protocol.CommandTypes.Formatonkey = "formatonkey"; - /* @internal */ - export const FormatFull: protocol.CommandTypes.FormatFull = "format-full"; - /* @internal */ - export const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull = "formatonkey-full"; - /* @internal */ - export const FormatRangeFull: protocol.CommandTypes.FormatRangeFull = "formatRange-full"; - export const Geterr: protocol.CommandTypes.Geterr = "geterr"; - export const GeterrForProject: protocol.CommandTypes.GeterrForProject = "geterrForProject"; - export const Implementation: protocol.CommandTypes.Implementation = "implementation"; - /* @internal */ - export const ImplementationFull: protocol.CommandTypes.ImplementationFull = "implementation-full"; - export const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - export const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - export const NavBar: protocol.CommandTypes.NavBar = "navbar"; - /* @internal */ - export const NavBarFull: protocol.CommandTypes.NavBarFull = "navbar-full"; - export const NavTree: protocol.CommandTypes.NavTree = "navtree"; - export const NavTreeFull: protocol.CommandTypes.NavTreeFull = "navtree-full"; - export const Navto: protocol.CommandTypes.Navto = "navto"; - /* @internal */ - export const NavtoFull: protocol.CommandTypes.NavtoFull = "navto-full"; - export const Occurrences: protocol.CommandTypes.Occurrences = "occurrences"; - export const DocumentHighlights: protocol.CommandTypes.DocumentHighlights = "documentHighlights"; - /* @internal */ - export const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull = "documentHighlights-full"; - export const Open: protocol.CommandTypes.Open = "open"; - export const Quickinfo: protocol.CommandTypes.Quickinfo = "quickinfo"; - /* @internal */ - export const QuickinfoFull: protocol.CommandTypes.QuickinfoFull = "quickinfo-full"; - export const References: protocol.CommandTypes.References = "references"; - /* @internal */ - export const ReferencesFull: protocol.CommandTypes.ReferencesFull = "references-full"; - export const Reload: protocol.CommandTypes.Reload = "reload"; - export const Rename: protocol.CommandTypes.Rename = "rename"; - /* @internal */ - export const RenameInfoFull: protocol.CommandTypes.RenameInfoFull = "rename-full"; - /* @internal */ - export const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull = "renameLocations-full"; - export const Saveto: protocol.CommandTypes.Saveto = "saveto"; - export const SignatureHelp: protocol.CommandTypes.SignatureHelp = "signatureHelp"; - /* @internal */ - export const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull = "signatureHelp-full"; - export const TypeDefinition: protocol.CommandTypes.TypeDefinition = "typeDefinition"; - export const ProjectInfo: protocol.CommandTypes.ProjectInfo = "projectInfo"; - export const ReloadProjects: protocol.CommandTypes.ReloadProjects = "reloadProjects"; - export const Unknown: protocol.CommandTypes.Unknown = "unknown"; - export const OpenExternalProject: protocol.CommandTypes.OpenExternalProject = "openExternalProject"; - export const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects = "openExternalProjects"; - export const CloseExternalProject: protocol.CommandTypes.CloseExternalProject = "closeExternalProject"; - /* @internal */ - export const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList = "synchronizeProjectList"; - /* @internal */ - export const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - /* @internal */ - export const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - /* @internal */ - export const Cleanup: protocol.CommandTypes.Cleanup = "cleanup"; - /* @internal */ - export const OutliningSpans: protocol.CommandTypes.OutliningSpans = "outliningSpans"; - export const TodoComments: protocol.CommandTypes.TodoComments = "todoComments"; - export const Indentation: protocol.CommandTypes.Indentation = "indentation"; - export const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate = "docCommentTemplate"; - /* @internal */ - export const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - /* @internal */ - export const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan = "nameOrDottedNameSpan"; - /* @internal */ - export const BreakpointStatement: protocol.CommandTypes.BreakpointStatement = "breakpointStatement"; - export const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - export const GetCodeFixes: protocol.CommandTypes.GetCodeFixes = "getCodeFixes"; - /* @internal */ - export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full"; - export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes"; - - export const GetApplicableRefactors: protocol.CommandTypes.GetApplicableRefactors = "getApplicableRefactors"; - export const GetRefactorCodeActions: protocol.CommandTypes.GetRefactorCodeActions = "getRefactorCodeActions"; - export const GetRefactorCodeActionsFull: protocol.CommandTypes.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; - } + export import CommandNames = protocol.CommandTypes; export function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string { const verboseLogging = logger.hasLevel(LogLevel.verbose); diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 0deff253212..acee8fe4b0e 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -573,7 +573,7 @@ namespace ts { } } - function getClassificationTypeName(type: ClassificationType) { + function getClassificationTypeName(type: ClassificationType): ClassificationTypeNames { switch (type) { case ClassificationType.comment: return ClassificationTypeNames.comment; case ClassificationType.identifier: return ClassificationTypeNames.identifier; diff --git a/src/services/types.ts b/src/services/types.ts index 6f0b3baf532..6e6fa245e37 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -286,7 +286,7 @@ namespace ts { export interface ClassifiedSpan { textSpan: TextSpan; - classificationType: string; // ClassificationTypeNames + classificationType: ClassificationTypeNames; } /** @@ -804,43 +804,43 @@ namespace ts { jsxAttribute = "JSX attribute", } - export namespace ScriptElementKindModifier { - export const none = ""; - export const publicMemberModifier = "public"; - export const privateMemberModifier = "private"; - export const protectedMemberModifier = "protected"; - export const exportedModifier = "export"; - export const ambientModifier = "declare"; - export const staticModifier = "static"; - export const abstractModifier = "abstract"; + export const enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", } - export class ClassificationTypeNames { - public static comment = "comment"; - public static identifier = "identifier"; - public static keyword = "keyword"; - public static numericLiteral = "number"; - public static operator = "operator"; - public static stringLiteral = "string"; - public static whiteSpace = "whitespace"; - public static text = "text"; + export const enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", - public static punctuation = "punctuation"; + punctuation = "punctuation", - public static className = "class name"; - public static enumName = "enum name"; - public static interfaceName = "interface name"; - public static moduleName = "module name"; - public static typeParameterName = "type parameter name"; - public static typeAliasName = "type alias name"; - public static parameterName = "parameter name"; - public static docCommentTagName = "doc comment tag name"; - public static jsxOpenTagName = "jsx open tag name"; - public static jsxCloseTagName = "jsx close tag name"; - public static jsxSelfClosingTagName = "jsx self closing tag name"; - public static jsxAttribute = "jsx attribute"; - public static jsxText = "jsx text"; - public static jsxAttributeStringLiteralValue = "jsx attribute string literal value"; + className = "class name", + enumName = "enum name", + interfaceName = "interface name", + moduleName = "module name", + typeParameterName = "type parameter name", + typeAliasName = "type alias name", + parameterName = "parameter name", + docCommentTagName = "doc comment tag name", + jsxOpenTagName = "jsx open tag name", + jsxCloseTagName = "jsx close tag name", + jsxSelfClosingTagName = "jsx self closing tag name", + jsxAttribute = "jsx attribute", + jsxText = "jsx text", + jsxAttributeStringLiteralValue = "jsx attribute string literal value", } export const enum ClassificationType { From 3b56ebeabe424547bcfba2eca77a9d74891901b8 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 22 May 2017 10:47:28 -0700 Subject: [PATCH 257/282] Convert other namespace + type alias in protocol.ts to const enums --- src/harness/unittests/session.ts | 12 +++--- src/server/protocol.ts | 68 +++++++++++++------------------- 2 files changed, 34 insertions(+), 46 deletions(-) diff --git a/src/harness/unittests/session.ts b/src/harness/unittests/session.ts index a505c3ee7be..74d1f5d0640 100644 --- a/src/harness/unittests/session.ts +++ b/src/harness/unittests/session.ts @@ -134,7 +134,7 @@ namespace ts.server { type: "request", arguments: { formatOptions: { - indentStyle: "Block" + indentStyle: protocol.IndentStyle.Block, } } }; @@ -149,11 +149,11 @@ namespace ts.server { type: "request", arguments: { options: { - module: "System", - target: "ES5", - jsx: "React", - newLine: "Lf", - moduleResolution: "Node" + module: protocol.ModuleKind.System, + target: protocol.ScriptTarget.ES5, + jsx: protocol.JsxEmit.React, + newLine: protocol.NewLineKind.Lf, + moduleResolution: protocol.ModuleResolutionKind.Node, } } }; diff --git a/src/server/protocol.ts b/src/server/protocol.ts index c51743e1c39..d398555408b 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2291,14 +2291,12 @@ namespace ts.server.protocol { body?: NavigationTree; } - export namespace IndentStyle { - export type None = "None"; - export type Block = "Block"; - export type Smart = "Smart"; + export const enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart", } - export type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; - export interface EditorSettings { baseIndentSize?: number; indentSize?: number; @@ -2395,47 +2393,37 @@ namespace ts.server.protocol { [option: string]: CompilerOptionsValue | undefined; } - export namespace JsxEmit { - export type None = "None"; - export type Preserve = "Preserve"; - export type ReactNative = "ReactNative"; - export type React = "React"; + export const enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React", } - export type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React | JsxEmit.ReactNative; - - export namespace ModuleKind { - export type None = "None"; - export type CommonJS = "CommonJS"; - export type AMD = "AMD"; - export type UMD = "UMD"; - export type System = "System"; - export type ES6 = "ES6"; - export type ES2015 = "ES2015"; + export const enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", } - export type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; - - export namespace ModuleResolutionKind { - export type Classic = "Classic"; - export type Node = "Node"; + export const enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node", } - export type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; - - export namespace NewLineKind { - export type Crlf = "Crlf"; - export type Lf = "Lf"; + export const enum NewLineKind { + Crlf, + Lf, } - export type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; - - export namespace ScriptTarget { - export type ES3 = "ES3"; - export type ES5 = "ES5"; - export type ES6 = "ES6"; - export type ES2015 = "ES2015"; + export const enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", } - - export type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; } From c6e69dd64ba26a29900e7f296d2df3cc8d22767d Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 22 May 2017 11:05:30 -0700 Subject: [PATCH 258/282] Fix missing initializers --- src/server/protocol.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/server/protocol.ts b/src/server/protocol.ts index d398555408b..8a75311c5d1 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2416,8 +2416,8 @@ namespace ts.server.protocol { } export const enum NewLineKind { - Crlf, - Lf, + Crlf = "Crlf", + Lf = "Lf", } export const enum ScriptTarget { From f6240cb6f91fb202c8c0b8fc21d965fd83ea62b7 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 22 May 2017 11:17:12 -0700 Subject: [PATCH 259/282] Make CommandTypes a const enum and use `allCommandTypes` for unit test --- src/harness/unittests/session.ts | 77 ++++++++++++++++++++++++++++++-- src/server/protocol.ts | 3 +- 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/src/harness/unittests/session.ts b/src/harness/unittests/session.ts index 74d1f5d0640..db33d87f087 100644 --- a/src/harness/unittests/session.ts +++ b/src/harness/unittests/session.ts @@ -172,12 +172,81 @@ namespace ts.server { }); describe("onMessage", () => { + const allCommandNames: CommandNames[] = [ + CommandNames.Brace, + CommandNames.BraceFull, + CommandNames.BraceCompletion, + CommandNames.Change, + CommandNames.Close, + CommandNames.Completions, + CommandNames.CompletionsFull, + CommandNames.CompletionDetails, + CommandNames.CompileOnSaveAffectedFileList, + CommandNames.Configure, + CommandNames.Definition, + CommandNames.DefinitionFull, + CommandNames.Implementation, + CommandNames.ImplementationFull, + CommandNames.Exit, + CommandNames.Format, + CommandNames.Formatonkey, + CommandNames.FormatFull, + CommandNames.FormatonkeyFull, + CommandNames.FormatRangeFull, + CommandNames.Geterr, + CommandNames.GeterrForProject, + CommandNames.SemanticDiagnosticsSync, + CommandNames.SyntacticDiagnosticsSync, + CommandNames.NavBar, + CommandNames.NavBarFull, + CommandNames.Navto, + CommandNames.NavtoFull, + CommandNames.NavTree, + CommandNames.NavTreeFull, + CommandNames.Occurrences, + CommandNames.DocumentHighlights, + CommandNames.DocumentHighlightsFull, + CommandNames.Open, + CommandNames.Quickinfo, + CommandNames.QuickinfoFull, + CommandNames.References, + CommandNames.ReferencesFull, + CommandNames.Reload, + CommandNames.Rename, + CommandNames.RenameInfoFull, + CommandNames.RenameLocationsFull, + CommandNames.Saveto, + CommandNames.SignatureHelp, + CommandNames.SignatureHelpFull, + CommandNames.TypeDefinition, + CommandNames.ProjectInfo, + CommandNames.ReloadProjects, + CommandNames.Unknown, + CommandNames.OpenExternalProject, + CommandNames.CloseExternalProject, + CommandNames.SynchronizeProjectList, + CommandNames.ApplyChangedToOpenFiles, + CommandNames.EncodedSemanticClassificationsFull, + CommandNames.Cleanup, + CommandNames.OutliningSpans, + CommandNames.TodoComments, + CommandNames.Indentation, + CommandNames.DocCommentTemplate, + CommandNames.CompilerOptionsDiagnosticsFull, + CommandNames.NameOrDottedNameSpan, + CommandNames.BreakpointStatement, + CommandNames.CompilerOptionsForInferredProjects, + CommandNames.GetCodeFixes, + CommandNames.GetCodeFixesFull, + CommandNames.GetSupportedCodeFixes, + CommandNames.GetApplicableRefactors, + CommandNames.GetRefactorCodeActions, + CommandNames.GetRefactorCodeActionsFull, + ]; + it("should not throw when commands are executed with invalid arguments", () => { let i = 0; - for (const name in CommandNames) { - if (!Object.prototype.hasOwnProperty.call(CommandNames, name)) { - continue; - } + for (const name of allCommandNames) { const req: protocol.Request = { command: name, seq: i, diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 8a75311c5d1..4e474edd0c4 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2,7 +2,8 @@ * Declaration module describing the TypeScript Server protocol */ namespace ts.server.protocol { - export enum CommandTypes { + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. + export const enum CommandTypes { Brace = "brace", /* @internal */ BraceFull = "brace-full", From 860e8e88c830eebf44bbdebdb86fadcf995f21bd Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 22 May 2017 14:49:35 -0700 Subject: [PATCH 260/282] Add error for class exprs w/private properties --- src/compiler/checker.ts | 13 +++++++------ src/compiler/declarationEmitter.ts | 8 ++++---- src/compiler/diagnosticMessages.json | 4 ++-- src/compiler/types.ts | 2 +- src/compiler/utilities.ts | 2 +- src/services/utilities.ts | 2 +- 6 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index cae9f2dac25..b01c145c24b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3352,8 +3352,6 @@ namespace ts { getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class; if (isConstructorObject) { - // TODO: something needs to issue accessibility errors (here, I think) - // before writing a literal type that flattens base types, check that the base types are accessible writeLiteralType(type, flags); } else { @@ -3479,10 +3477,13 @@ namespace ts { buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, IndexKind.String, enclosingDeclaration, globalFlags, symbolStack); buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, IndexKind.Number, enclosingDeclaration, globalFlags, symbolStack); for (const p of resolved.properties) { - if (globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral && - (p.name === "prototype" || - getDeclarationModifierFlagsFromSymbol(p) & (ModifierFlags.Private | ModifierFlags.Protected))) { - continue; + if (globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral) { + if (p.flags & SymbolFlags.Prototype) { + continue; + } + if (getDeclarationModifierFlagsFromSymbol(p) & (ModifierFlags.Private | ModifierFlags.Protected)) { + writer.reportPrivateInBaseOfClassExpression(p.name); + } } const t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 89358872a0f..3cc85aaa24b 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -190,7 +190,7 @@ namespace ts { const writer = createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; - writer.reportIllegalExtends = reportIllegalExtends; + writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; writer.writePunctuation = writer.write; @@ -314,11 +314,11 @@ namespace ts { recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } - function reportIllegalExtends() { + function reportPrivateInBaseOfClassExpression(propertyName: string) { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, - declarationNameToString(errorNameNode))); + emitterDiagnostics.add( + createDiagnosticForNode(errorNameNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4aee7a37a88..c5b74943dcd 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2432,9 +2432,9 @@ "category": "Error", "code": 4092 }, - "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced.": { + "Property '{0}' of exported class expression may not be private or protected.": { "category": "Error", - "code": 4093 + "code": 4094 }, "The current host does not support the '{0}' option.": { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 069f8b967cf..0cade7f2cbc 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2648,7 +2648,7 @@ namespace ts { // with import statements it previously saw (but chose not to emit). trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; - reportIllegalExtends(): void; + reportPrivateInBaseOfClassExpression(propertyName: string): void; } export const enum TypeFormatFlags { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index befb1c4ba77..3c3710c1cc5 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -68,7 +68,7 @@ namespace ts { clear: () => str = "", trackSymbol: noop, reportInaccessibleThisError: noop, - reportIllegalExtends: noop + reportPrivateInBaseOfClassExpression: noop, }; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index c8b710789ad..0965eb4dad7 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1128,7 +1128,7 @@ namespace ts { clear: resetWriter, trackSymbol: noop, reportInaccessibleThisError: noop, - reportIllegalExtends: noop + reportPrivateInBaseOfClassExpression: noop, }; function writeIndent() { From ecaf44d47437204f88ef11813665c1c38d32c6c3 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Mon, 22 May 2017 14:57:56 -0700 Subject: [PATCH 261/282] Add more tests and update baselines --- .../emitClassExpressionInDeclarationFile.js | 16 ---- ...assExpressionInDeclarationFile2.errors.txt | 41 +++++++++ .../emitClassExpressionInDeclarationFile2.js | 87 +++++++++++++++++++ .../emitClassExpressionInDeclarationFile.ts | 7 -- .../emitClassExpressionInDeclarationFile2.ts | 29 +++++++ 5 files changed, 157 insertions(+), 23 deletions(-) create mode 100644 tests/baselines/reference/emitClassExpressionInDeclarationFile2.errors.txt create mode 100644 tests/baselines/reference/emitClassExpressionInDeclarationFile2.js create mode 100644 tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile.js b/tests/baselines/reference/emitClassExpressionInDeclarationFile.js index 423546bcd4e..ab64fe003be 100644 --- a/tests/baselines/reference/emitClassExpressionInDeclarationFile.js +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile.js @@ -95,18 +95,12 @@ export declare var simpleExample: { new (): { tags(): void; }; - prototype: { - tags(): void; - }; getTags(): void; }; export declare var circularReference: { new (): { tags(c: any): any; }; - prototype: { - tags(c: any): any; - }; getTags(c: { tags(c: any): any; }): { @@ -124,11 +118,6 @@ export declare function WithTags>(Base: T): { foo(): void; name?: string; }; - prototype: { - tags(): void; - foo(): void; - name?: string; - }; getTags(): void; } & T; declare const Test_base: { @@ -137,11 +126,6 @@ declare const Test_base: { foo(): void; name?: string; }; - prototype: { - tags(): void; - foo(): void; - name?: string; - }; getTags(): void; } & typeof FooItem; export declare class Test extends Test_base { diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile2.errors.txt b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.errors.txt new file mode 100644 index 00000000000..4541cf2a58a --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.errors.txt @@ -0,0 +1,41 @@ +tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(1,12): error TS4094: Property 'p' of exported class expression may not be private or protected. +tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(1,12): error TS4094: Property 'ps' of exported class expression may not be private or protected. +tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(16,17): error TS4094: Property 'property' of exported class expression may not be private or protected. + + +==== tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts (3 errors) ==== + export var noPrivates = class { + ~~~~~~~~~~ +!!! error TS4094: Property 'p' of exported class expression may not be private or protected. + ~~~~~~~~~~ +!!! error TS4094: Property 'ps' of exported class expression may not be private or protected. + static getTags() { } + tags() { } + private static ps = -1 + private p = 12 + } + + // altered repro from #15066 to add private property + export class FooItem { + foo(): void { } + name?: string; + private property = "capitalism" + } + + export type Constructor = new(...args: any[]) => T; + export function WithTags>(Base: T) { + ~~~~~~~~ +!!! error TS4094: Property 'property' of exported class expression may not be private or protected. + return class extends Base { + static getTags(): void { } + tags(): void { } + } + } + + export class Test extends WithTags(FooItem) {} + + const test = new Test(); + + Test.getTags() + test.tags(); + \ No newline at end of file diff --git a/tests/baselines/reference/emitClassExpressionInDeclarationFile2.js b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.js new file mode 100644 index 00000000000..e3a0aa4cb99 --- /dev/null +++ b/tests/baselines/reference/emitClassExpressionInDeclarationFile2.js @@ -0,0 +1,87 @@ +//// [emitClassExpressionInDeclarationFile2.ts] +export var noPrivates = class { + static getTags() { } + tags() { } + private static ps = -1 + private p = 12 +} + +// altered repro from #15066 to add private property +export class FooItem { + foo(): void { } + name?: string; + private property = "capitalism" +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); + + +//// [emitClassExpressionInDeclarationFile2.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +exports.noPrivates = (_a = (function () { + function class_1() { + this.p = 12; + } + class_1.getTags = function () { }; + class_1.prototype.tags = function () { }; + return class_1; + }()), + _a.ps = -1, + _a); +// altered repro from #15066 to add private property +var FooItem = (function () { + function FooItem() { + this.property = "capitalism"; + } + FooItem.prototype.foo = function () { }; + return FooItem; +}()); +exports.FooItem = FooItem; +function WithTags(Base) { + return (function (_super) { + __extends(class_2, _super); + function class_2() { + return _super !== null && _super.apply(this, arguments) || this; + } + class_2.getTags = function () { }; + class_2.prototype.tags = function () { }; + return class_2; + }(Base)); +} +exports.WithTags = WithTags; +var Test = (function (_super) { + __extends(Test, _super); + function Test() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Test; +}(WithTags(FooItem))); +exports.Test = Test; +var test = new Test(); +Test.getTags(); +test.tags(); +var _a; diff --git a/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts index 4268f237044..f99bcbd7efd 100644 --- a/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts +++ b/tests/cases/compiler/emitClassExpressionInDeclarationFile.ts @@ -2,19 +2,12 @@ export var simpleExample = class { static getTags() { } tags() { } - private static ps = -1 - private p = 12 } export var circularReference = class C { static getTags(c: C): C { return c } tags(c: C): C { return c } } -class Base { } -export function foo() { - return class extends Base { } -} - // repro from #15066 export class FooItem { foo(): void { } diff --git a/tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts b/tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts new file mode 100644 index 00000000000..3175f2afce7 --- /dev/null +++ b/tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts @@ -0,0 +1,29 @@ +// @declaration: true +export var noPrivates = class { + static getTags() { } + tags() { } + private static ps = -1 + private p = 12 +} + +// altered repro from #15066 to add private property +export class FooItem { + foo(): void { } + name?: string; + private property = "capitalism" +} + +export type Constructor = new(...args: any[]) => T; +export function WithTags>(Base: T) { + return class extends Base { + static getTags(): void { } + tags(): void { } + } +} + +export class Test extends WithTags(FooItem) {} + +const test = new Test(); + +Test.getTags() +test.tags(); From 05498be4410d7eaca3a3fb6a0ff0d352c9861597 Mon Sep 17 00:00:00 2001 From: Ika Date: Tue, 23 May 2017 06:58:35 +0800 Subject: [PATCH 262/282] Add missing undefined type (#15999) --- src/compiler/factory.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 965cb5fdda5..2b41f13f8a4 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -1631,14 +1631,14 @@ namespace ts { : node; } - export function createImportClause(name: Identifier, namedBindings: NamedImportBindings): ImportClause { + export function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause { const node = createSynthesizedNode(SyntaxKind.ImportClause); node.name = name; node.namedBindings = namedBindings; return node; } - export function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings) { + export function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) { return node.name !== name || node.namedBindings !== namedBindings ? updateNode(createImportClause(name, namedBindings), node) From 1f8cf313e133556a742b90accf387adf2f1938b5 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 22 May 2017 16:12:55 -0700 Subject: [PATCH 263/282] Port lib changes 5 22 2017 (#16005) * Port lib changes * Update LKG --- lib/lib.d.ts | 8697 ++++++++-------- lib/lib.dom.d.ts | 8649 ++++++++-------- lib/lib.es2015.iterable.d.ts | 78 +- lib/lib.es2015.proxy.d.ts | 2 +- lib/lib.es2016.full.d.ts | 8649 ++++++++-------- lib/lib.es2017.full.d.ts | 8649 ++++++++-------- lib/lib.es2017.sharedmemory.d.ts | 93 +- lib/lib.es5.d.ts | 48 +- lib/lib.es6.d.ts | 8777 ++++++++--------- lib/lib.esnext.full.d.ts | 8649 ++++++++-------- lib/lib.webworker.d.ts | 279 +- lib/protocol.d.ts | 41 +- lib/tsc.js | 4195 ++++---- lib/tsserver.js | 6726 ++++++++----- lib/tsserverlibrary.d.ts | 321 +- lib/tsserverlibrary.js | 6712 ++++++++----- lib/typescript.d.ts | 280 +- lib/typescript.js | 7353 ++++++++------ lib/typescriptServices.d.ts | 280 +- lib/typescriptServices.js | 7353 ++++++++------ lib/typingsInstaller.js | 253 +- src/lib/dom.generated.d.ts | 8649 ++++++++-------- src/lib/webworker.generated.d.ts | 279 +- .../modularizeLibrary_Dom.iterable.types | 4 +- 24 files changed, 49890 insertions(+), 45126 deletions(-) diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 80e09b844cb..e5868efa1f2 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4281,15 +4289,15 @@ interface Date { ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -4302,32 +4310,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -4367,13 +4375,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -4387,15 +4388,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -4404,17 +4405,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -4424,9 +4432,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -4439,6 +4446,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -4451,17 +4459,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -4488,11 +4496,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -4517,39 +4525,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -4561,31 +4683,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -4603,8 +4730,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -4614,12 +4741,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -4627,35 +4754,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -4665,28 +4792,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -4704,13 +4831,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -4718,241 +4845,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -4961,39 +4969,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -5003,9 +5011,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -5014,14 +5022,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -5030,8 +5038,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -5041,38 +5049,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -5080,15 +5113,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -5103,19 +5136,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -5125,285 +5158,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -5415,13 +5423,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -5430,11 +5438,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -5442,10 +5450,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -5464,19 +5472,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -5492,8 +5487,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -5503,7 +5511,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -5548,7 +5556,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -5561,7 +5569,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -5576,7 +5584,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -5599,7 +5607,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -5645,7 +5653,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -5654,7 +5662,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -5667,7 +5675,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -5686,7 +5694,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -5702,7 +5710,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -5713,7 +5721,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -5727,7 +5735,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -5750,7 +5758,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -5759,7 +5767,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -5768,13 +5776,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -5782,7 +5790,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -5795,16 +5803,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -5817,7 +6114,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -5826,7 +6123,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -5837,7 +6134,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -5848,7 +6145,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -5858,7 +6155,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -5871,7 +6168,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -5880,7 +6177,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -5890,7 +6187,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -5902,7 +6199,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -5912,8 +6209,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -5929,8 +6226,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -5938,7 +6235,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -5949,13 +6246,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -6031,9 +6328,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -6103,24 +6400,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -6256,9 +6553,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -6310,7 +6607,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -6321,7 +6618,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -6347,7 +6644,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -6355,296 +6652,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -6654,150 +6662,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -6808,7 +6673,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -6825,7 +6690,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -6838,7 +6703,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -6852,7 +6717,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -6865,7 +6730,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -6874,7 +6739,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -6885,7 +6750,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -6894,7 +6759,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -6907,7 +6772,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -6920,7 +6785,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -6931,7 +6796,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -7026,299 +6891,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -7338,146 +7195,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -7486,243 +7351,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7731,7 +7596,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -7740,7 +7605,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -7754,8 +7619,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -7765,7 +7773,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -7779,27 +7787,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -7880,9 +7868,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -7900,18 +7888,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -7922,9 +7910,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7933,7 +7921,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -7947,12 +7935,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -7979,7 +7967,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -7990,8 +7978,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -8005,7 +8013,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -8013,7 +8021,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -8024,7 +8032,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -8035,7 +8043,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -8050,7 +8058,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -8060,7 +8068,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -8074,7 +8082,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -8088,7 +8096,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -8097,7 +8105,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -8112,7 +8120,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -8122,7 +8130,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -8131,7 +8139,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -8142,8 +8150,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -8154,87 +8202,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8243,70 +8291,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -8317,66 +8365,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8385,7 +8433,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -8393,7 +8441,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -8403,30 +8451,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8435,16 +8469,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8453,7 +8487,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -8512,71 +8546,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8585,32 +8633,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -8620,42 +8668,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -8666,7 +8703,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -8677,7 +8714,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -8688,16 +8725,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8706,8 +8743,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8716,7 +8764,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -8889,54 +8937,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8945,39 +8993,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -8986,12 +9034,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9000,7 +9048,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -9009,74 +9057,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9086,7 +9134,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -9094,68 +9142,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9164,7 +9212,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -9191,33 +9239,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -9233,8 +9281,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9243,29 +9291,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -9276,12 +9302,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9290,12 +9316,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9304,7 +9352,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -9312,79 +9360,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9393,86 +9441,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -9484,210 +9532,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9696,31 +9744,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9729,16 +9762,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9747,41 +9780,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -9792,16 +9840,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9810,7 +9858,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -9842,7 +9890,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -9851,162 +9899,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -10033,7 +10081,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -10045,32 +10093,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10079,7 +10127,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -10095,16 +10143,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10113,13 +10161,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10129,154 +10294,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10285,37 +10333,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10324,7 +10372,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -10336,7 +10384,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -10358,12 +10406,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10373,24 +10421,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10399,7 +10447,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10409,12 +10457,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10423,24 +10471,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10449,12 +10497,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10463,38 +10511,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10504,94 +10552,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10601,18 +10649,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -10626,7 +10674,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10636,17 +10684,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10655,16 +10703,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10673,53 +10721,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10728,20 +10776,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10750,7 +10798,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10760,111 +10808,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10873,12 +10921,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10887,39 +10935,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10928,26 +10976,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10956,7 +11004,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -10967,105 +11015,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11074,7 +11122,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -11085,12 +11133,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11099,7 +11147,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -11124,7 +11172,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -11136,7 +11184,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11146,7 +11194,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -11156,8 +11204,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -11169,31 +11217,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11201,47 +11249,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -11265,7 +11273,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -11274,7 +11282,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -11291,7 +11299,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11300,7 +11308,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -11311,7 +11319,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -11322,14 +11330,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -11345,7 +11353,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -11361,14 +11369,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -11385,7 +11393,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -11393,7 +11401,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -11407,7 +11415,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -11417,7 +11425,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -11437,7 +11445,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -11447,7 +11455,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -11456,7 +11464,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -11468,7 +11476,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -11483,7 +11491,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -11497,7 +11505,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -11532,7 +11540,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -11542,7 +11550,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -11563,7 +11571,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -11573,8 +11581,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -11623,7 +12013,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -11633,7 +12023,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -11643,7 +12033,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -11653,7 +12043,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -11665,7 +12055,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -11676,7 +12066,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -11685,7 +12075,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -11696,7 +12086,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -11732,7 +12122,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -11742,7 +12132,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -11776,7 +12166,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -11802,7 +12192,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -11831,7 +12221,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -11853,7 +12243,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -11863,7 +12253,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -11872,8 +12262,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -11885,19 +12287,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -11920,7 +12310,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -11931,7 +12321,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -11941,7 +12331,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -11952,7 +12342,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -11968,7 +12358,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -12003,7 +12393,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -12013,389 +12403,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -12415,7 +12423,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -12426,7 +12434,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -12443,7 +12451,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -12460,7 +12468,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -12470,7 +12478,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -12479,7 +12487,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -12488,7 +12496,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -12515,7 +12523,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -12590,7 +12598,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -12613,7 +12621,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -12628,7 +12636,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -12639,7 +12647,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -12669,7 +12677,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -12677,7 +12685,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -12687,7 +12695,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -12695,7 +12703,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -12703,7 +12711,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -12713,7 +12721,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -12721,7 +12729,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -12730,7 +12738,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -12748,7 +12756,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -12769,7 +12777,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -12786,7 +12794,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -12795,7 +12803,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -12814,7 +12822,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -12822,7 +12830,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -12842,7 +12850,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -12864,7 +12872,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -12873,7 +12881,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -12890,8 +12898,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -12919,157 +13077,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -13077,7 +13085,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -13087,7 +13095,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -13096,7 +13104,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -13112,7 +13120,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -13125,7 +13133,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -13148,7 +13156,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -13158,7 +13166,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -13168,7 +13176,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -13185,7 +13193,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -13194,7 +13202,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -13206,7 +13214,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -13217,7 +13225,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -13230,7 +13238,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -13240,17 +13248,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -13273,7 +13378,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -13282,7 +13387,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -13303,19 +13408,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -13324,7 +13438,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -13345,7 +13459,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -13354,7 +13468,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -13383,7 +13497,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -13392,7 +13506,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -13438,7 +13552,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -13447,7 +13561,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -13471,7 +13585,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -13496,7 +13610,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -13507,7 +13621,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -13524,7 +13638,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -13533,7 +13647,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -13543,112 +13657,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -13658,7 +14081,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -13682,7 +14105,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -13692,7 +14115,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -13702,7 +14125,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -13712,7 +14135,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -13722,7 +14145,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -13732,7 +14155,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -13742,7 +14165,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -13752,7 +14175,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -13762,7 +14185,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -13772,7 +14195,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -13782,7 +14205,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -13792,7 +14215,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -13802,7 +14225,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -13815,7 +14238,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -13826,7 +14249,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -13855,7 +14278,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -13865,7 +14288,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -13875,7 +14298,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -13913,7 +14336,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -13929,7 +14352,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -13939,7 +14362,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -13953,7 +14376,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14000,7 +14423,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14023,7 +14446,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14034,7 +14457,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14065,7 +14488,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -14095,7 +14518,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -14110,7 +14533,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14135,7 +14558,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -14147,7 +14570,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14157,7 +14580,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14167,7 +14590,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14177,7 +14600,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14187,7 +14610,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14197,7 +14620,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14211,7 +14634,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -14222,7 +14645,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14232,7 +14655,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -14243,7 +14666,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14263,7 +14686,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -14276,7 +14699,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -14289,7 +14712,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14305,7 +14728,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -14323,7 +14746,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14334,7 +14757,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -14362,7 +14785,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -14381,7 +14804,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -14395,7 +14818,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14405,7 +14828,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -14426,7 +14849,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -14443,7 +14866,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -14458,7 +14881,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -14494,7 +14917,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -14510,21 +14933,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -14538,8 +14947,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -14550,12 +14973,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -14563,13 +14986,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -14585,7 +15008,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -14610,7 +15033,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -14620,7 +15043,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -14629,7 +15052,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -14645,7 +15068,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -14678,7 +15101,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -14728,7 +15151,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -14743,7 +15166,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -14758,7 +15181,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -14766,7 +15189,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -14780,7 +15203,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -14794,7 +15217,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -14806,7 +15229,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -14818,7 +15241,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -14830,7 +15253,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -14842,7 +15265,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -14852,7 +15275,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -14862,7 +15285,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -14872,7 +15295,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -14881,7 +15304,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -14890,7 +15313,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -14900,7 +15323,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -14909,7 +15332,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -14918,7 +15341,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -14934,7 +15357,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -14944,7 +15367,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -14954,7 +15377,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -14971,7 +15394,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -14982,7 +15405,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -14998,7 +15421,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15008,7 +15431,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15018,7 +15441,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -15056,7 +15479,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -15071,7 +15494,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -15083,7 +15506,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -15099,8 +15522,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -15160,59 +15635,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15222,7 +15645,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15232,17 +15655,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -15269,7 +15682,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15279,7 +15692,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -15304,7 +15717,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -15319,7 +15732,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15329,7 +15742,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -15360,7 +15773,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -15378,8 +15791,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -15401,7 +15824,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -15412,7 +15835,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -15422,7 +15845,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -15435,420 +15858,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -15858,7 +15868,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -15869,7 +15879,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -15901,7 +15911,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -15910,7 +15920,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -15953,7 +15963,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -15977,7 +15987,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -15989,7 +15999,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -16007,7 +16017,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -16018,7 +16028,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -16034,7 +16044,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -16052,7 +16062,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -16063,7 +16073,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -16072,7 +16082,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -16083,7 +16093,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -16103,7 +16113,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -16114,8 +16124,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -16137,16 +16156,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -16164,7 +16174,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -16177,7 +16187,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -16191,7 +16201,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -16215,45 +16225,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -16263,7 +16235,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -16273,7 +16245,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -16285,8 +16257,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -16296,7 +16306,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -16304,7 +16314,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -16313,7 +16323,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -16321,7 +16331,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -16329,7 +16339,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -16337,7 +16347,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -16345,7 +16355,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -16606,13 +16616,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -16637,9 +16647,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -16669,18 +16679,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -16714,6 +16724,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -16746,23 +16770,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -16908,13 +16918,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -16939,9 +16949,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -16971,18 +16981,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -17016,6 +17026,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -17048,23 +17072,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -17088,7 +17098,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -17096,7 +17106,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -17107,7 +17117,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -17115,7 +17125,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -17123,7 +17133,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -17163,7 +17173,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -17172,7 +17182,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -17181,7 +17191,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -17194,7 +17204,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -17203,7 +17213,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -17213,7 +17223,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -17223,8 +17233,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -17260,7 +17280,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -17283,7 +17303,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -17311,6 +17331,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -17369,6 +17390,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -17382,8 +17407,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -17506,9 +17531,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -17564,7 +17589,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -17581,7 +17606,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -17591,7 +17616,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -17638,7 +17663,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -17648,7 +17673,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -17657,7 +17682,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -17668,7 +17693,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -17677,7 +17702,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -17686,7 +17711,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -17723,7 +17748,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -17739,17 +17764,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -17786,6 +17801,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -17794,81 +17884,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -17913,16 +17928,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -18147,38 +18162,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -18426,7 +18441,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -18476,8 +18491,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -18485,59 +18542,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -18625,48 +18640,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -18691,307 +18685,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -18999,8 +18753,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -19123,9 +18877,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -19244,6 +18998,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -19257,6 +19012,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -19264,12 +19025,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -19281,6 +19036,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -19288,9 +19051,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -19301,14 +19064,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 94fb13c32ed..1bf904d60d4 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -20,15 +20,15 @@ and limitations under the License. ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -41,32 +41,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -106,13 +106,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -126,15 +119,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -143,17 +136,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -163,9 +163,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -178,6 +177,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -190,17 +190,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -227,11 +227,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -256,39 +256,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -300,31 +414,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -342,8 +461,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -353,12 +472,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -366,35 +485,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -404,28 +523,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -443,13 +562,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -457,241 +576,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -700,39 +700,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -742,9 +742,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -753,14 +753,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -769,8 +769,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -780,38 +780,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -819,15 +844,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -842,19 +867,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -864,285 +889,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -1154,13 +1154,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -1169,11 +1169,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -1181,10 +1181,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -1203,19 +1203,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1231,8 +1218,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1242,7 +1242,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -1287,7 +1287,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -1300,7 +1300,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -1315,7 +1315,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -1338,7 +1338,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -1384,7 +1384,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -1393,7 +1393,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -1406,7 +1406,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -1425,7 +1425,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -1441,7 +1441,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -1452,7 +1452,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -1466,7 +1466,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -1489,7 +1489,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -1498,7 +1498,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -1507,13 +1507,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1521,7 +1521,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -1534,16 +1534,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -1556,7 +1845,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -1565,7 +1854,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1576,7 +1865,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -1587,7 +1876,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -1597,7 +1886,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1610,7 +1899,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -1619,7 +1908,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -1629,7 +1918,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -1641,7 +1930,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -1651,8 +1940,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1668,8 +1957,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1677,7 +1966,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -1688,13 +1977,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -1770,9 +2059,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -1842,24 +2131,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -1995,9 +2284,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2049,7 +2338,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -2060,7 +2349,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -2086,7 +2375,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -2094,296 +2383,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -2393,150 +2393,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -2547,7 +2404,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -2564,7 +2421,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -2577,7 +2434,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -2591,7 +2448,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -2604,7 +2461,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -2613,7 +2470,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -2624,7 +2481,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -2633,7 +2490,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -2646,7 +2503,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -2659,7 +2516,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -2670,7 +2527,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -2765,299 +2622,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -3077,146 +2926,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -3225,243 +3082,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3470,7 +3327,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -3479,7 +3336,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -3493,8 +3350,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -3504,7 +3504,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -3518,27 +3518,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -3619,9 +3599,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -3639,18 +3619,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -3661,9 +3641,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3672,7 +3652,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -3686,12 +3666,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -3718,7 +3698,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -3729,8 +3709,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -3744,7 +3744,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -3752,7 +3752,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -3763,7 +3763,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -3774,7 +3774,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -3789,7 +3789,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -3799,7 +3799,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -3813,7 +3813,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -3827,7 +3827,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -3836,7 +3836,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -3851,7 +3851,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -3861,7 +3861,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -3870,7 +3870,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -3881,8 +3881,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -3893,87 +3933,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3982,70 +4022,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -4056,66 +4096,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4124,7 +4164,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -4132,7 +4172,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4142,30 +4182,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4174,16 +4200,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4192,7 +4218,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4251,71 +4277,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4324,32 +4364,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4359,42 +4399,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -4405,7 +4434,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -4416,7 +4445,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -4427,16 +4456,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4445,8 +4474,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4455,7 +4495,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -4628,54 +4668,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4684,39 +4724,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4725,12 +4765,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4739,7 +4779,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -4748,74 +4788,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4825,7 +4865,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -4833,68 +4873,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4903,7 +4943,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4930,33 +4970,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -4972,8 +5012,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4982,29 +5022,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -5015,12 +5033,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5029,12 +5047,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5043,7 +5083,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -5051,79 +5091,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5132,86 +5172,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -5223,210 +5263,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5435,31 +5475,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5468,16 +5493,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5486,41 +5511,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -5531,16 +5571,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5549,7 +5589,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -5581,7 +5621,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -5590,162 +5630,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -5772,7 +5812,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -5784,32 +5824,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5818,7 +5858,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -5834,16 +5874,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5852,13 +5892,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -5868,154 +6025,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6024,37 +6064,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6063,7 +6103,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -6075,7 +6115,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -6097,12 +6137,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6112,24 +6152,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6138,7 +6178,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6148,12 +6188,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6162,24 +6202,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6188,12 +6228,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6202,38 +6242,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6243,94 +6283,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6340,18 +6380,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -6365,7 +6405,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6375,17 +6415,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6394,16 +6434,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6412,53 +6452,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6467,20 +6507,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6489,7 +6529,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6499,111 +6539,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6612,12 +6652,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6626,39 +6666,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6667,26 +6707,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6695,7 +6735,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -6706,105 +6746,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6813,7 +6853,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -6824,12 +6864,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6838,7 +6878,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -6863,7 +6903,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -6875,7 +6915,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6885,7 +6925,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -6895,8 +6935,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -6908,31 +6948,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6940,47 +6980,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -7004,7 +7004,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -7013,7 +7013,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -7030,7 +7030,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7039,7 +7039,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -7050,7 +7050,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -7061,14 +7061,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -7084,7 +7084,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -7100,14 +7100,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -7124,7 +7124,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -7132,7 +7132,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -7146,7 +7146,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -7156,7 +7156,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -7176,7 +7176,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -7186,7 +7186,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -7195,7 +7195,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -7207,7 +7207,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -7222,7 +7222,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -7236,7 +7236,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -7271,7 +7271,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -7281,7 +7281,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -7302,7 +7302,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -7312,8 +7312,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -7362,7 +7744,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -7372,7 +7754,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -7382,7 +7764,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -7392,7 +7774,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -7404,7 +7786,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -7415,7 +7797,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -7424,7 +7806,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -7435,7 +7817,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -7471,7 +7853,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -7481,7 +7863,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -7515,7 +7897,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -7541,7 +7923,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -7570,7 +7952,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -7592,7 +7974,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -7602,7 +7984,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -7611,8 +7993,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -7624,19 +8018,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -7659,7 +8041,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -7670,7 +8052,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -7680,7 +8062,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -7691,7 +8073,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -7707,7 +8089,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -7742,7 +8124,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -7752,389 +8134,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -8154,7 +8154,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -8165,7 +8165,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -8182,7 +8182,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -8199,7 +8199,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -8209,7 +8209,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -8218,7 +8218,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -8227,7 +8227,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -8254,7 +8254,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -8329,7 +8329,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -8352,7 +8352,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -8367,7 +8367,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -8378,7 +8378,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -8408,7 +8408,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -8416,7 +8416,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -8426,7 +8426,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -8434,7 +8434,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -8442,7 +8442,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -8452,7 +8452,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -8460,7 +8460,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -8469,7 +8469,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -8487,7 +8487,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -8508,7 +8508,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -8525,7 +8525,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -8534,7 +8534,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -8553,7 +8553,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -8561,7 +8561,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -8581,7 +8581,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -8603,7 +8603,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -8612,7 +8612,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -8629,8 +8629,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -8658,157 +8808,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -8816,7 +8816,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -8826,7 +8826,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -8835,7 +8835,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -8851,7 +8851,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -8864,7 +8864,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -8887,7 +8887,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -8897,7 +8897,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -8907,7 +8907,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -8924,7 +8924,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -8933,7 +8933,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -8945,7 +8945,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -8956,7 +8956,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -8969,7 +8969,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -8979,17 +8979,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -9012,7 +9109,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -9021,7 +9118,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -9042,19 +9139,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -9063,7 +9169,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -9084,7 +9190,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -9093,7 +9199,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -9122,7 +9228,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -9131,7 +9237,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -9177,7 +9283,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -9186,7 +9292,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -9210,7 +9316,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -9235,7 +9341,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -9246,7 +9352,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -9263,7 +9369,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -9272,7 +9378,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -9282,112 +9388,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9397,7 +9812,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -9421,7 +9836,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -9431,7 +9846,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -9441,7 +9856,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -9451,7 +9866,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -9461,7 +9876,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -9471,7 +9886,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -9481,7 +9896,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -9491,7 +9906,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -9501,7 +9916,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -9511,7 +9926,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -9521,7 +9936,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -9531,7 +9946,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -9541,7 +9956,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9554,7 +9969,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -9565,7 +9980,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -9594,7 +10009,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9604,7 +10019,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9614,7 +10029,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -9652,7 +10067,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -9668,7 +10083,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -9678,7 +10093,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9692,7 +10107,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9739,7 +10154,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9762,7 +10177,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9773,7 +10188,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9804,7 +10219,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -9834,7 +10249,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -9849,7 +10264,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9874,7 +10289,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -9886,7 +10301,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9896,7 +10311,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9906,7 +10321,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9916,7 +10331,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9926,7 +10341,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9936,7 +10351,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9950,7 +10365,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -9961,7 +10376,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9971,7 +10386,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -9982,7 +10397,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10002,7 +10417,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -10015,7 +10430,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -10028,7 +10443,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10044,7 +10459,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -10062,7 +10477,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10073,7 +10488,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -10101,7 +10516,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -10120,7 +10535,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10134,7 +10549,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10144,7 +10559,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -10165,7 +10580,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -10182,7 +10597,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10197,7 +10612,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -10233,7 +10648,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -10249,21 +10664,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -10277,8 +10678,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -10289,12 +10704,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10302,13 +10717,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -10324,7 +10739,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -10349,7 +10764,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10359,7 +10774,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -10368,7 +10783,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -10384,7 +10799,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -10417,7 +10832,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -10467,7 +10882,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -10482,7 +10897,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -10497,7 +10912,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -10505,7 +10920,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -10519,7 +10934,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -10533,7 +10948,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -10545,7 +10960,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -10557,7 +10972,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -10569,7 +10984,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -10581,7 +10996,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -10591,7 +11006,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -10601,7 +11016,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -10611,7 +11026,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -10620,7 +11035,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -10629,7 +11044,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -10639,7 +11054,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -10648,7 +11063,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -10657,7 +11072,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -10673,7 +11088,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -10683,7 +11098,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -10693,7 +11108,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10710,7 +11125,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -10721,7 +11136,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -10737,7 +11152,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10747,7 +11162,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10757,7 +11172,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -10795,7 +11210,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -10810,7 +11225,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -10822,7 +11237,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10838,8 +11253,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -10899,59 +11366,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10961,7 +11376,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10971,17 +11386,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -11008,7 +11413,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11018,7 +11423,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -11043,7 +11448,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -11058,7 +11463,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11068,7 +11473,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -11099,7 +11504,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -11117,8 +11522,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11140,7 +11555,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -11151,7 +11566,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -11161,7 +11576,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -11174,420 +11589,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -11597,7 +11599,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -11608,7 +11610,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -11640,7 +11642,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -11649,7 +11651,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -11692,7 +11694,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -11716,7 +11718,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -11728,7 +11730,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -11746,7 +11748,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -11757,7 +11759,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -11773,7 +11775,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -11791,7 +11793,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -11802,7 +11804,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -11811,7 +11813,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -11822,7 +11824,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -11842,7 +11844,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -11853,8 +11855,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -11876,16 +11887,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -11903,7 +11905,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -11916,7 +11918,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -11930,7 +11932,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -11954,45 +11956,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -12002,7 +11966,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -12012,7 +11976,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -12024,8 +11988,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -12035,7 +12037,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -12043,7 +12045,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -12052,7 +12054,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -12060,7 +12062,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -12068,7 +12070,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -12076,7 +12078,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -12084,7 +12086,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -12345,13 +12347,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12376,9 +12378,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12408,18 +12410,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12453,6 +12455,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12485,23 +12501,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12647,13 +12649,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12678,9 +12680,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12710,18 +12712,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12755,6 +12757,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12787,23 +12803,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12827,7 +12829,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -12835,7 +12837,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -12846,7 +12848,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -12854,7 +12856,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -12862,7 +12864,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -12902,7 +12904,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -12911,7 +12913,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -12920,7 +12922,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -12933,7 +12935,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -12942,7 +12944,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -12952,7 +12954,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -12962,8 +12964,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -12999,7 +13011,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -13022,7 +13034,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -13050,6 +13062,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -13108,6 +13121,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -13121,8 +13138,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13245,9 +13262,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13303,7 +13320,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -13320,7 +13337,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -13330,7 +13347,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -13377,7 +13394,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -13387,7 +13404,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -13396,7 +13413,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -13407,7 +13424,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -13416,7 +13433,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -13425,7 +13442,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -13462,7 +13479,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -13478,17 +13495,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -13525,6 +13532,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -13533,81 +13615,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -13652,16 +13659,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -13886,38 +13893,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -14165,7 +14172,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -14215,8 +14222,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -14224,59 +14273,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -14364,48 +14371,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -14430,307 +14416,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -14738,8 +14484,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -14862,9 +14608,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -14983,6 +14729,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -14996,6 +14743,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -15003,12 +14756,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -15020,6 +14767,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -15027,9 +14782,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -15040,14 +14795,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 1fe1a0e0ca1..551698607ca 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -52,17 +52,17 @@ interface Array { [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -86,21 +86,21 @@ interface ArrayConstructor { } interface ReadonlyArray { - /** Iterator */ + /** Iterator of values in the array. */ [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -111,9 +111,42 @@ interface IArguments { } interface Map { + /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ values(): IterableIterator; } @@ -128,9 +161,40 @@ interface WeakMapConstructor { } interface Set { + /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ values(): IterableIterator; } diff --git a/lib/lib.es2015.proxy.d.ts b/lib/lib.es2015.proxy.d.ts index 29b12d91e24..440897038ef 100644 --- a/lib/lib.es2015.proxy.d.ts +++ b/lib/lib.es2015.proxy.d.ts @@ -23,7 +23,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 737357fef6d..ea4cdd0577f 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -23,15 +23,15 @@ and limitations under the License. ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -44,32 +44,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -109,13 +109,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -129,15 +122,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -146,17 +139,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -166,9 +166,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -181,6 +180,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -193,17 +193,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -230,11 +230,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -259,39 +259,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -303,31 +417,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -345,8 +464,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -356,12 +475,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -369,35 +488,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -407,28 +526,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -446,13 +565,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -460,241 +579,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -703,39 +703,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -745,9 +745,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -756,14 +756,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -772,8 +772,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -783,38 +783,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -822,15 +847,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -845,19 +870,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -867,285 +892,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -1157,13 +1157,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -1172,11 +1172,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -1184,10 +1184,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -1206,19 +1206,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1234,8 +1221,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1245,7 +1245,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -1290,7 +1290,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -1303,7 +1303,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -1318,7 +1318,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -1341,7 +1341,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -1387,7 +1387,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -1396,7 +1396,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -1409,7 +1409,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -1428,7 +1428,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -1444,7 +1444,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -1455,7 +1455,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -1469,7 +1469,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -1492,7 +1492,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -1501,7 +1501,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -1510,13 +1510,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1524,7 +1524,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -1537,16 +1537,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -1559,7 +1848,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -1568,7 +1857,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1579,7 +1868,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -1590,7 +1879,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -1600,7 +1889,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1613,7 +1902,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -1622,7 +1911,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -1632,7 +1921,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -1644,7 +1933,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -1654,8 +1943,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1671,8 +1960,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1680,7 +1969,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -1691,13 +1980,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -1773,9 +2062,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -1845,24 +2134,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -1998,9 +2287,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2052,7 +2341,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -2063,7 +2352,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -2089,7 +2378,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -2097,296 +2386,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -2396,150 +2396,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -2550,7 +2407,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -2567,7 +2424,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -2580,7 +2437,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -2594,7 +2451,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -2607,7 +2464,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -2616,7 +2473,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -2627,7 +2484,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -2636,7 +2493,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -2649,7 +2506,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -2662,7 +2519,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -2673,7 +2530,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -2768,299 +2625,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -3080,146 +2929,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -3228,243 +3085,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3473,7 +3330,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -3482,7 +3339,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -3496,8 +3353,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -3507,7 +3507,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -3521,27 +3521,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -3622,9 +3602,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -3642,18 +3622,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -3664,9 +3644,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3675,7 +3655,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -3689,12 +3669,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -3721,7 +3701,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -3732,8 +3712,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -3747,7 +3747,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -3755,7 +3755,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -3766,7 +3766,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -3777,7 +3777,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -3792,7 +3792,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -3802,7 +3802,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -3816,7 +3816,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -3830,7 +3830,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -3839,7 +3839,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -3854,7 +3854,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -3864,7 +3864,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -3873,7 +3873,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -3884,8 +3884,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -3896,87 +3936,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3985,70 +4025,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -4059,66 +4099,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4127,7 +4167,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -4135,7 +4175,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4145,30 +4185,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4177,16 +4203,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4195,7 +4221,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4254,71 +4280,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4327,32 +4367,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4362,42 +4402,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -4408,7 +4437,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -4419,7 +4448,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -4430,16 +4459,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4448,8 +4477,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4458,7 +4498,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -4631,54 +4671,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4687,39 +4727,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4728,12 +4768,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4742,7 +4782,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -4751,74 +4791,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4828,7 +4868,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -4836,68 +4876,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4906,7 +4946,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4933,33 +4973,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -4975,8 +5015,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4985,29 +5025,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -5018,12 +5036,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5032,12 +5050,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5046,7 +5086,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -5054,79 +5094,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5135,86 +5175,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -5226,210 +5266,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5438,31 +5478,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5471,16 +5496,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5489,41 +5514,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -5534,16 +5574,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5552,7 +5592,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -5584,7 +5624,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -5593,162 +5633,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -5775,7 +5815,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -5787,32 +5827,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5821,7 +5861,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -5837,16 +5877,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5855,13 +5895,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -5871,154 +6028,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6027,37 +6067,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6066,7 +6106,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -6078,7 +6118,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -6100,12 +6140,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6115,24 +6155,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6141,7 +6181,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6151,12 +6191,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6165,24 +6205,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6191,12 +6231,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6205,38 +6245,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6246,94 +6286,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6343,18 +6383,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -6368,7 +6408,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6378,17 +6418,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6397,16 +6437,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6415,53 +6455,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6470,20 +6510,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6492,7 +6532,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6502,111 +6542,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6615,12 +6655,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6629,39 +6669,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6670,26 +6710,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6698,7 +6738,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -6709,105 +6749,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6816,7 +6856,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -6827,12 +6867,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6841,7 +6881,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -6866,7 +6906,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -6878,7 +6918,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6888,7 +6928,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -6898,8 +6938,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -6911,31 +6951,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6943,47 +6983,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -7007,7 +7007,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -7016,7 +7016,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -7033,7 +7033,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7042,7 +7042,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -7053,7 +7053,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -7064,14 +7064,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -7087,7 +7087,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -7103,14 +7103,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -7127,7 +7127,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -7135,7 +7135,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -7149,7 +7149,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -7159,7 +7159,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -7179,7 +7179,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -7189,7 +7189,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -7198,7 +7198,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -7210,7 +7210,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -7225,7 +7225,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -7239,7 +7239,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -7274,7 +7274,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -7284,7 +7284,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -7305,7 +7305,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -7315,8 +7315,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -7365,7 +7747,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -7375,7 +7757,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -7385,7 +7767,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -7395,7 +7777,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -7407,7 +7789,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -7418,7 +7800,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -7427,7 +7809,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -7438,7 +7820,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -7474,7 +7856,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -7484,7 +7866,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -7518,7 +7900,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -7544,7 +7926,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -7573,7 +7955,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -7595,7 +7977,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -7605,7 +7987,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -7614,8 +7996,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -7627,19 +8021,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -7662,7 +8044,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -7673,7 +8055,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -7683,7 +8065,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -7694,7 +8076,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -7710,7 +8092,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -7745,7 +8127,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -7755,389 +8137,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -8157,7 +8157,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -8168,7 +8168,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -8185,7 +8185,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -8202,7 +8202,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -8212,7 +8212,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -8221,7 +8221,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -8230,7 +8230,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -8257,7 +8257,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -8332,7 +8332,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -8355,7 +8355,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -8370,7 +8370,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -8381,7 +8381,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -8411,7 +8411,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -8419,7 +8419,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -8429,7 +8429,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -8437,7 +8437,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -8445,7 +8445,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -8455,7 +8455,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -8463,7 +8463,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -8472,7 +8472,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -8490,7 +8490,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -8511,7 +8511,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -8528,7 +8528,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -8537,7 +8537,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -8556,7 +8556,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -8564,7 +8564,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -8584,7 +8584,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -8606,7 +8606,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -8615,7 +8615,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -8632,8 +8632,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -8661,157 +8811,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -8819,7 +8819,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -8829,7 +8829,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -8838,7 +8838,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -8854,7 +8854,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -8867,7 +8867,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -8890,7 +8890,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -8900,7 +8900,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -8910,7 +8910,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -8927,7 +8927,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -8936,7 +8936,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -8948,7 +8948,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -8959,7 +8959,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -8972,7 +8972,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -8982,17 +8982,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -9015,7 +9112,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -9024,7 +9121,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -9045,19 +9142,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -9066,7 +9172,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -9087,7 +9193,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -9096,7 +9202,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -9125,7 +9231,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -9134,7 +9240,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -9180,7 +9286,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -9189,7 +9295,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -9213,7 +9319,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -9238,7 +9344,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -9249,7 +9355,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -9266,7 +9372,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -9275,7 +9381,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -9285,112 +9391,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9400,7 +9815,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -9424,7 +9839,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -9434,7 +9849,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -9444,7 +9859,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -9454,7 +9869,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -9464,7 +9879,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -9474,7 +9889,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -9484,7 +9899,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -9494,7 +9909,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -9504,7 +9919,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -9514,7 +9929,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -9524,7 +9939,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -9534,7 +9949,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -9544,7 +9959,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9557,7 +9972,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -9568,7 +9983,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -9597,7 +10012,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9607,7 +10022,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9617,7 +10032,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -9655,7 +10070,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -9671,7 +10086,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -9681,7 +10096,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9695,7 +10110,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9742,7 +10157,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9765,7 +10180,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9776,7 +10191,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9807,7 +10222,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -9837,7 +10252,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -9852,7 +10267,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9877,7 +10292,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -9889,7 +10304,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9899,7 +10314,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9909,7 +10324,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9919,7 +10334,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9929,7 +10344,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9939,7 +10354,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9953,7 +10368,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -9964,7 +10379,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9974,7 +10389,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -9985,7 +10400,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10005,7 +10420,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -10018,7 +10433,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -10031,7 +10446,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10047,7 +10462,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -10065,7 +10480,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10076,7 +10491,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -10104,7 +10519,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -10123,7 +10538,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10137,7 +10552,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10147,7 +10562,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -10168,7 +10583,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -10185,7 +10600,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10200,7 +10615,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -10236,7 +10651,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -10252,21 +10667,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -10280,8 +10681,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -10292,12 +10707,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10305,13 +10720,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -10327,7 +10742,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -10352,7 +10767,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10362,7 +10777,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -10371,7 +10786,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -10387,7 +10802,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -10420,7 +10835,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -10470,7 +10885,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -10485,7 +10900,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -10500,7 +10915,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -10508,7 +10923,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -10522,7 +10937,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -10536,7 +10951,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -10548,7 +10963,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -10560,7 +10975,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -10572,7 +10987,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -10584,7 +10999,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -10594,7 +11009,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -10604,7 +11019,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -10614,7 +11029,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -10623,7 +11038,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -10632,7 +11047,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -10642,7 +11057,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -10651,7 +11066,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -10660,7 +11075,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -10676,7 +11091,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -10686,7 +11101,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -10696,7 +11111,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10713,7 +11128,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -10724,7 +11139,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -10740,7 +11155,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10750,7 +11165,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10760,7 +11175,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -10798,7 +11213,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -10813,7 +11228,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -10825,7 +11240,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10841,8 +11256,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -10902,59 +11369,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10964,7 +11379,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10974,17 +11389,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -11011,7 +11416,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11021,7 +11426,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -11046,7 +11451,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -11061,7 +11466,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11071,7 +11476,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -11102,7 +11507,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -11120,8 +11525,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11143,7 +11558,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -11154,7 +11569,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -11164,7 +11579,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -11177,420 +11592,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -11600,7 +11602,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -11611,7 +11613,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -11643,7 +11645,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -11652,7 +11654,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -11695,7 +11697,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -11719,7 +11721,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -11731,7 +11733,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -11749,7 +11751,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -11760,7 +11762,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -11776,7 +11778,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -11794,7 +11796,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -11805,7 +11807,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -11814,7 +11816,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -11825,7 +11827,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -11845,7 +11847,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -11856,8 +11858,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -11879,16 +11890,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -11906,7 +11908,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -11919,7 +11921,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -11933,7 +11935,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -11957,45 +11959,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -12005,7 +11969,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -12015,7 +11979,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -12027,8 +11991,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -12038,7 +12040,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -12046,7 +12048,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -12055,7 +12057,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -12063,7 +12065,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -12071,7 +12073,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -12079,7 +12081,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -12087,7 +12089,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -12348,13 +12350,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12379,9 +12381,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12411,18 +12413,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12456,6 +12458,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12488,23 +12504,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12650,13 +12652,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12681,9 +12683,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12713,18 +12715,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12758,6 +12760,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12790,23 +12806,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12830,7 +12832,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -12838,7 +12840,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -12849,7 +12851,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -12857,7 +12859,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -12865,7 +12867,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -12905,7 +12907,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -12914,7 +12916,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -12923,7 +12925,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -12936,7 +12938,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -12945,7 +12947,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -12955,7 +12957,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -12965,8 +12967,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -13002,7 +13014,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -13025,7 +13037,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -13053,6 +13065,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -13111,6 +13124,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -13124,8 +13141,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13248,9 +13265,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13306,7 +13323,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -13323,7 +13340,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -13333,7 +13350,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -13380,7 +13397,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -13390,7 +13407,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -13399,7 +13416,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -13410,7 +13427,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -13419,7 +13436,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -13428,7 +13445,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -13465,7 +13482,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -13481,17 +13498,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -13528,6 +13535,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -13536,81 +13618,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -13655,16 +13662,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -13889,38 +13896,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -14168,7 +14175,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -14218,8 +14225,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -14227,59 +14276,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -14367,48 +14374,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -14433,307 +14419,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -14741,8 +14487,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -14865,9 +14611,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -14986,6 +14732,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -14999,6 +14746,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -15006,12 +14759,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -15023,6 +14770,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -15030,9 +14785,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -15043,14 +14798,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index dae59bc9ae3..6c1c9906295 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -25,15 +25,15 @@ and limitations under the License. ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -46,32 +46,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -111,13 +111,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -131,15 +124,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -148,17 +141,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -168,9 +168,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -183,6 +182,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -195,17 +195,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -232,11 +232,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -261,39 +261,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -305,31 +419,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -347,8 +466,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -358,12 +477,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -371,35 +490,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -409,28 +528,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -448,13 +567,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -462,241 +581,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -705,39 +705,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -747,9 +747,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -758,14 +758,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -774,8 +774,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -785,38 +785,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -824,15 +849,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -847,19 +872,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -869,285 +894,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -1159,13 +1159,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -1174,11 +1174,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -1186,10 +1186,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -1208,19 +1208,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1236,8 +1223,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1247,7 +1247,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -1292,7 +1292,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -1305,7 +1305,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -1320,7 +1320,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -1343,7 +1343,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -1389,7 +1389,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -1398,7 +1398,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -1411,7 +1411,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -1430,7 +1430,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -1446,7 +1446,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -1457,7 +1457,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -1471,7 +1471,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -1494,7 +1494,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -1503,7 +1503,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -1512,13 +1512,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1526,7 +1526,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -1539,16 +1539,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -1561,7 +1850,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -1570,7 +1859,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1581,7 +1870,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -1592,7 +1881,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -1602,7 +1891,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1615,7 +1904,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -1624,7 +1913,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -1634,7 +1923,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -1646,7 +1935,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -1656,8 +1945,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1673,8 +1962,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1682,7 +1971,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -1693,13 +1982,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -1775,9 +2064,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -1847,24 +2136,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -2000,9 +2289,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2054,7 +2343,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -2065,7 +2354,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -2091,7 +2380,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -2099,296 +2388,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -2398,150 +2398,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -2552,7 +2409,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -2569,7 +2426,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -2582,7 +2439,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -2596,7 +2453,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -2609,7 +2466,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -2618,7 +2475,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -2629,7 +2486,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -2638,7 +2495,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -2651,7 +2508,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -2664,7 +2521,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -2675,7 +2532,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -2770,299 +2627,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -3082,146 +2931,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -3230,243 +3087,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3475,7 +3332,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -3484,7 +3341,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -3498,8 +3355,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -3509,7 +3509,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -3523,27 +3523,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -3624,9 +3604,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -3644,18 +3624,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -3666,9 +3646,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3677,7 +3657,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -3691,12 +3671,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -3723,7 +3703,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -3734,8 +3714,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -3749,7 +3749,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -3757,7 +3757,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -3768,7 +3768,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -3779,7 +3779,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -3794,7 +3794,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -3804,7 +3804,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -3818,7 +3818,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -3832,7 +3832,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -3841,7 +3841,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -3856,7 +3856,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -3866,7 +3866,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -3875,7 +3875,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -3886,8 +3886,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -3898,87 +3938,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3987,70 +4027,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -4061,66 +4101,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4129,7 +4169,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -4137,7 +4177,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4147,30 +4187,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4179,16 +4205,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4197,7 +4223,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4256,71 +4282,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4329,32 +4369,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4364,42 +4404,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -4410,7 +4439,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -4421,7 +4450,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -4432,16 +4461,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4450,8 +4479,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4460,7 +4500,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -4633,54 +4673,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4689,39 +4729,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4730,12 +4770,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4744,7 +4784,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -4753,74 +4793,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4830,7 +4870,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -4838,68 +4878,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4908,7 +4948,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4935,33 +4975,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -4977,8 +5017,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4987,29 +5027,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -5020,12 +5038,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5034,12 +5052,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5048,7 +5088,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -5056,79 +5096,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5137,86 +5177,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -5228,210 +5268,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5440,31 +5480,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5473,16 +5498,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5491,41 +5516,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -5536,16 +5576,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5554,7 +5594,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -5586,7 +5626,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -5595,162 +5635,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -5777,7 +5817,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -5789,32 +5829,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5823,7 +5863,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -5839,16 +5879,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5857,13 +5897,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -5873,154 +6030,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6029,37 +6069,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6068,7 +6108,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -6080,7 +6120,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -6102,12 +6142,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6117,24 +6157,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6143,7 +6183,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6153,12 +6193,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6167,24 +6207,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6193,12 +6233,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6207,38 +6247,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6248,94 +6288,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6345,18 +6385,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -6370,7 +6410,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6380,17 +6420,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6399,16 +6439,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6417,53 +6457,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6472,20 +6512,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6494,7 +6534,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6504,111 +6544,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6617,12 +6657,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6631,39 +6671,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6672,26 +6712,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6700,7 +6740,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -6711,105 +6751,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6818,7 +6858,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -6829,12 +6869,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6843,7 +6883,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -6868,7 +6908,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -6880,7 +6920,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6890,7 +6930,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -6900,8 +6940,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -6913,31 +6953,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6945,47 +6985,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -7009,7 +7009,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -7018,7 +7018,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -7035,7 +7035,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7044,7 +7044,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -7055,7 +7055,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -7066,14 +7066,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -7089,7 +7089,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -7105,14 +7105,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -7129,7 +7129,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -7137,7 +7137,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -7151,7 +7151,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -7161,7 +7161,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -7181,7 +7181,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -7191,7 +7191,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -7200,7 +7200,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -7212,7 +7212,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -7227,7 +7227,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -7241,7 +7241,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -7276,7 +7276,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -7286,7 +7286,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -7307,7 +7307,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -7317,8 +7317,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -7367,7 +7749,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -7377,7 +7759,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -7387,7 +7769,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -7397,7 +7779,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -7409,7 +7791,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -7420,7 +7802,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -7429,7 +7811,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -7440,7 +7822,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -7476,7 +7858,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -7486,7 +7868,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -7520,7 +7902,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -7546,7 +7928,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -7575,7 +7957,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -7597,7 +7979,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -7607,7 +7989,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -7616,8 +7998,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -7629,19 +8023,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -7664,7 +8046,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -7675,7 +8057,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -7685,7 +8067,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -7696,7 +8078,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -7712,7 +8094,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -7747,7 +8129,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -7757,389 +8139,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -8159,7 +8159,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -8170,7 +8170,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -8187,7 +8187,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -8204,7 +8204,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -8214,7 +8214,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -8223,7 +8223,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -8232,7 +8232,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -8259,7 +8259,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -8334,7 +8334,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -8357,7 +8357,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -8372,7 +8372,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -8383,7 +8383,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -8413,7 +8413,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -8421,7 +8421,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -8431,7 +8431,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -8439,7 +8439,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -8447,7 +8447,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -8457,7 +8457,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -8465,7 +8465,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -8474,7 +8474,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -8492,7 +8492,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -8513,7 +8513,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -8530,7 +8530,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -8539,7 +8539,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -8558,7 +8558,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -8566,7 +8566,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -8586,7 +8586,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -8608,7 +8608,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -8617,7 +8617,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -8634,8 +8634,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -8663,157 +8813,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -8821,7 +8821,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -8831,7 +8831,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -8840,7 +8840,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -8856,7 +8856,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -8869,7 +8869,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -8892,7 +8892,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -8902,7 +8902,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -8912,7 +8912,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -8929,7 +8929,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -8938,7 +8938,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -8950,7 +8950,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -8961,7 +8961,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -8974,7 +8974,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -8984,17 +8984,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -9017,7 +9114,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -9026,7 +9123,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -9047,19 +9144,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -9068,7 +9174,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -9089,7 +9195,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -9098,7 +9204,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -9127,7 +9233,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -9136,7 +9242,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -9182,7 +9288,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -9191,7 +9297,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -9215,7 +9321,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -9240,7 +9346,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -9251,7 +9357,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -9268,7 +9374,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -9277,7 +9383,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -9287,112 +9393,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9402,7 +9817,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -9426,7 +9841,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -9436,7 +9851,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -9446,7 +9861,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -9456,7 +9871,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -9466,7 +9881,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -9476,7 +9891,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -9486,7 +9901,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -9496,7 +9911,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -9506,7 +9921,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -9516,7 +9931,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -9526,7 +9941,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -9536,7 +9951,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -9546,7 +9961,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9559,7 +9974,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -9570,7 +9985,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -9599,7 +10014,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9609,7 +10024,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9619,7 +10034,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -9657,7 +10072,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -9673,7 +10088,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -9683,7 +10098,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9697,7 +10112,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9744,7 +10159,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9767,7 +10182,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9778,7 +10193,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9809,7 +10224,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -9839,7 +10254,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -9854,7 +10269,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9879,7 +10294,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -9891,7 +10306,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9901,7 +10316,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9911,7 +10326,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9921,7 +10336,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9931,7 +10346,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9941,7 +10356,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9955,7 +10370,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -9966,7 +10381,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9976,7 +10391,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -9987,7 +10402,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10007,7 +10422,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -10020,7 +10435,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -10033,7 +10448,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10049,7 +10464,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -10067,7 +10482,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10078,7 +10493,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -10106,7 +10521,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -10125,7 +10540,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10139,7 +10554,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10149,7 +10564,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -10170,7 +10585,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -10187,7 +10602,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10202,7 +10617,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -10238,7 +10653,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -10254,21 +10669,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -10282,8 +10683,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -10294,12 +10709,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10307,13 +10722,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -10329,7 +10744,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -10354,7 +10769,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10364,7 +10779,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -10373,7 +10788,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -10389,7 +10804,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -10422,7 +10837,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -10472,7 +10887,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -10487,7 +10902,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -10502,7 +10917,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -10510,7 +10925,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -10524,7 +10939,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -10538,7 +10953,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -10550,7 +10965,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -10562,7 +10977,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -10574,7 +10989,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -10586,7 +11001,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -10596,7 +11011,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -10606,7 +11021,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -10616,7 +11031,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -10625,7 +11040,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -10634,7 +11049,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -10644,7 +11059,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -10653,7 +11068,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -10662,7 +11077,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -10678,7 +11093,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -10688,7 +11103,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -10698,7 +11113,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10715,7 +11130,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -10726,7 +11141,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -10742,7 +11157,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10752,7 +11167,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10762,7 +11177,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -10800,7 +11215,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -10815,7 +11230,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -10827,7 +11242,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10843,8 +11258,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -10904,59 +11371,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10966,7 +11381,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10976,17 +11391,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -11013,7 +11418,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11023,7 +11428,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -11048,7 +11453,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -11063,7 +11468,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11073,7 +11478,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -11104,7 +11509,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -11122,8 +11527,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11145,7 +11560,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -11156,7 +11571,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -11166,7 +11581,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -11179,420 +11594,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -11602,7 +11604,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -11613,7 +11615,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -11645,7 +11647,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -11654,7 +11656,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -11697,7 +11699,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -11721,7 +11723,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -11733,7 +11735,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -11751,7 +11753,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -11762,7 +11764,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -11778,7 +11780,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -11796,7 +11798,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -11807,7 +11809,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -11816,7 +11818,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -11827,7 +11829,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -11847,7 +11849,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -11858,8 +11860,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -11881,16 +11892,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -11908,7 +11910,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -11921,7 +11923,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -11935,7 +11937,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -11959,45 +11961,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -12007,7 +11971,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -12017,7 +11981,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -12029,8 +11993,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -12040,7 +12042,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -12048,7 +12050,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -12057,7 +12059,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -12065,7 +12067,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -12073,7 +12075,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -12081,7 +12083,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -12089,7 +12091,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -12350,13 +12352,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12381,9 +12383,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12413,18 +12415,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12458,6 +12460,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12490,23 +12506,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12652,13 +12654,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12683,9 +12685,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12715,18 +12717,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12760,6 +12762,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12792,23 +12808,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12832,7 +12834,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -12840,7 +12842,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -12851,7 +12853,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -12859,7 +12861,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -12867,7 +12869,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -12907,7 +12909,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -12916,7 +12918,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -12925,7 +12927,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -12938,7 +12940,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -12947,7 +12949,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -12957,7 +12959,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -12967,8 +12969,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -13004,7 +13016,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -13027,7 +13039,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -13055,6 +13067,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -13113,6 +13126,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -13126,8 +13143,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13250,9 +13267,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13308,7 +13325,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -13325,7 +13342,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -13335,7 +13352,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -13382,7 +13399,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -13392,7 +13409,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -13401,7 +13418,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -13412,7 +13429,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -13421,7 +13438,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -13430,7 +13447,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -13467,7 +13484,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -13483,17 +13500,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -13530,6 +13537,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -13538,81 +13620,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -13657,16 +13664,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -13891,38 +13898,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -14170,7 +14177,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -14220,8 +14227,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -14229,59 +14278,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -14369,48 +14376,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -14435,307 +14421,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -14743,8 +14489,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -14867,9 +14613,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -14988,6 +14734,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -15001,6 +14748,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -15008,12 +14761,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -15025,6 +14772,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -15032,9 +14787,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -15045,14 +14800,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/lib/lib.es2017.sharedmemory.d.ts b/lib/lib.es2017.sharedmemory.d.ts index c0254f1dc2c..50a38686a90 100644 --- a/lib/lib.es2017.sharedmemory.d.ts +++ b/lib/lib.es2017.sharedmemory.d.ts @@ -43,5 +43,96 @@ interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; new (byteLength: number): SharedArrayBuffer; } +declare var SharedArrayBuffer: SharedArrayBufferConstructor; -declare var SharedArrayBuffer: SharedArrayBufferConstructor; \ No newline at end of file +interface ArrayBufferTypes { + SharedArrayBuffer: SharedArrayBuffer; +} + +interface Atomics { + /** + * Adds a value to the value at the given position in the array, returning the original value. + * Until this atomic operation completes, any other read or write operation against the array + * will block. + */ + add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores the bitwise AND of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or + * write operation against the array will block. + */ + and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Replaces the value at the given position in the array if the original value equals the given + * expected value, returning the original value. Until this atomic operation completes, any + * other read or write operation against the array will block. + */ + compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + + /** + * Replaces the value at the given position in the array, returning the original value. Until + * this atomic operation completes, any other read or write operation against the array will + * block. + */ + exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Returns a value indicating whether high-performance algorithms can use atomic operations + * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed + * array. + */ + isLockFree(size: number): boolean; + + /** + * Returns the value at the given position in the array. Until this atomic operation completes, + * any other read or write operation against the array will block. + */ + load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + + /** + * Stores the bitwise OR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Stores a value at the given position in the array, returning the new value. Until this + * atomic operation completes, any other read or write operation against the array will block. + */ + store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * Subtracts a value from the value at the given position in the array, returning the original + * value. Until this atomic operation completes, any other read or write operation against the + * array will block. + */ + sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + /** + * If the value at the given position in the array is equal to the provided value, the current + * agent is put to sleep causing execution to suspend until the timeout expires (returning + * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns + * `"not-equal"`. + */ + wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; + + /** + * Wakes up sleeping agents that are waiting on the given index of the array, returning the + * number of agents that were awoken. + */ + wake(typedArray: Int32Array, index: number, count: number): number; + + /** + * Stores the bitwise XOR of a value with the value at the given position in the array, + * returning the original value. Until this atomic operation completes, any other read or write + * operation against the array will block. + */ + xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + + readonly [Symbol.toStringTag]: "Atomics"; +} + +declare var Atomics: Atomics; \ No newline at end of file diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 1d19198d1d1..f359e519ab1 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 76dc84306ed..37d92454a25 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1406,6 +1406,14 @@ interface ArrayBuffer { slice(begin: number, end?: number): ArrayBuffer; } +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; @@ -1417,7 +1425,7 @@ interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1559,7 +1567,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1576,7 +1584,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor { readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1860,7 +1868,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2145,7 +2153,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2429,7 +2437,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor { readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2714,7 +2722,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2998,7 +3006,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor { readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3282,7 +3290,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3566,7 +3574,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor { readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3851,7 +3859,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBuffer; + readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. @@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor { readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4977,17 +4985,17 @@ interface Array { [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -5011,21 +5019,21 @@ interface ArrayConstructor { } interface ReadonlyArray { - /** Iterator */ + /** Iterator of values in the array. */ [Symbol.iterator](): IterableIterator; /** - * Returns an array of key, value pairs for every entry in the array + * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array + * Returns an iterable of keys in the array */ keys(): IterableIterator; /** - * Returns an list of values in the array + * Returns an iterable of values in the array */ values(): IterableIterator; } @@ -5036,9 +5044,42 @@ interface IArguments { } interface Map { + /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ + values(): IterableIterator; +} + +interface ReadonlyMap { + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](): IterableIterator<[K, V]>; + + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + entries(): IterableIterator<[K, V]>; + + /** + * Returns an iterable of keys in the map + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the map + */ values(): IterableIterator; } @@ -5053,9 +5094,40 @@ interface WeakMapConstructor { } interface Set { + /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator; + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ entries(): IterableIterator<[T, T]>; + /** + * Despite its name, returns an iterable of the values in the set, + */ keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ + values(): IterableIterator; +} + +interface ReadonlySet { + /** Iterates over values in the set. */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an iterable of [v,v] pairs for every value `v` in the set. + */ + entries(): IterableIterator<[T, T]>; + + /** + * Despite its name, returns an iterable of the values in the set, + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the set. + */ values(): IterableIterator; } @@ -5637,7 +5709,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; @@ -6041,15 +6113,15 @@ interface Float64Array { ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -6062,32 +6134,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -6127,13 +6199,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -6147,15 +6212,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -6164,17 +6229,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -6184,9 +6256,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -6199,6 +6270,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -6211,17 +6283,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -6248,11 +6320,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -6277,39 +6349,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -6321,31 +6507,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -6363,8 +6554,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -6374,12 +6565,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -6387,35 +6578,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -6425,28 +6616,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -6464,13 +6655,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -6478,241 +6669,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -6721,39 +6793,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -6763,9 +6835,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -6774,14 +6846,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -6790,8 +6862,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -6801,38 +6873,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -6840,15 +6937,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -6863,19 +6960,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -6885,285 +6982,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -7175,13 +7247,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -7190,11 +7262,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -7202,10 +7274,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -7224,19 +7296,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -7252,8 +7311,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -7263,7 +7335,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -7308,7 +7380,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -7321,7 +7393,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -7336,7 +7408,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -7359,7 +7431,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -7405,7 +7477,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -7414,7 +7486,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -7427,7 +7499,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -7446,7 +7518,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -7462,7 +7534,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -7473,7 +7545,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -7487,7 +7559,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -7510,7 +7582,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -7519,7 +7591,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -7528,13 +7600,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -7542,7 +7614,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -7555,16 +7627,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -7577,7 +7938,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -7586,7 +7947,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -7597,7 +7958,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -7608,7 +7969,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -7618,7 +7979,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -7631,7 +7992,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -7640,7 +8001,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -7650,7 +8011,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -7662,7 +8023,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -7672,8 +8033,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -7689,8 +8050,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -7698,7 +8059,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -7709,13 +8070,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -7791,9 +8152,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -7863,24 +8224,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -8016,9 +8377,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -8070,7 +8431,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -8081,7 +8442,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -8107,7 +8468,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -8115,296 +8476,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -8414,150 +8486,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -8568,7 +8497,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -8585,7 +8514,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -8598,7 +8527,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -8612,7 +8541,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -8625,7 +8554,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -8634,7 +8563,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -8645,7 +8574,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -8654,7 +8583,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -8667,7 +8596,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -8680,7 +8609,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -8691,7 +8620,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -8786,299 +8715,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -9098,146 +9019,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -9246,243 +9175,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9491,7 +9420,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -9500,7 +9429,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -9514,8 +9443,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -9525,7 +9597,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -9539,27 +9611,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -9640,9 +9692,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -9660,18 +9712,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -9682,9 +9734,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9693,7 +9745,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -9707,12 +9759,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -9739,7 +9791,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -9750,8 +9802,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -9765,7 +9837,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -9773,7 +9845,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -9784,7 +9856,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -9795,7 +9867,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -9810,7 +9882,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -9820,7 +9892,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -9834,7 +9906,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -9848,7 +9920,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -9857,7 +9929,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -9872,7 +9944,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -9882,7 +9954,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -9891,7 +9963,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -9902,8 +9974,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -9914,87 +10026,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10003,70 +10115,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -10077,66 +10189,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10145,7 +10257,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -10153,7 +10265,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10163,30 +10275,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10195,16 +10293,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10213,7 +10311,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -10272,71 +10370,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10345,32 +10457,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10380,42 +10492,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -10426,7 +10527,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -10437,7 +10538,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -10448,16 +10549,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10466,8 +10567,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10476,7 +10588,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -10649,54 +10761,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10705,39 +10817,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10746,12 +10858,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10760,7 +10872,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -10769,74 +10881,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10846,7 +10958,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -10854,68 +10966,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10924,7 +11036,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -10951,33 +11063,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -10993,8 +11105,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11003,29 +11115,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -11036,12 +11126,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11050,12 +11140,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11064,7 +11176,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -11072,79 +11184,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11153,86 +11265,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -11244,210 +11356,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11456,31 +11568,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11489,16 +11586,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11507,41 +11604,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -11552,16 +11664,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11570,7 +11682,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -11602,7 +11714,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -11611,162 +11723,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -11793,7 +11905,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -11805,32 +11917,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11839,7 +11951,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -11855,16 +11967,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11873,13 +11985,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11889,154 +12118,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12045,37 +12157,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12084,7 +12196,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -12096,7 +12208,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -12118,12 +12230,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -12133,24 +12245,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12159,7 +12271,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -12169,12 +12281,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12183,24 +12295,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12209,12 +12321,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12223,38 +12335,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -12264,94 +12376,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12361,18 +12473,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -12386,7 +12498,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -12396,17 +12508,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12415,16 +12527,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12433,53 +12545,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12488,20 +12600,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12510,7 +12622,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -12520,111 +12632,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12633,12 +12745,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12647,39 +12759,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12688,26 +12800,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12716,7 +12828,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -12727,105 +12839,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12834,7 +12946,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -12845,12 +12957,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12859,7 +12971,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -12884,7 +12996,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -12896,7 +13008,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -12906,7 +13018,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -12916,8 +13028,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -12929,31 +13041,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -12961,47 +13073,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -13025,7 +13097,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -13034,7 +13106,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -13051,7 +13123,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -13060,7 +13132,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -13071,7 +13143,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -13082,14 +13154,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -13105,7 +13177,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -13121,14 +13193,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -13145,7 +13217,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -13153,7 +13225,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -13167,7 +13239,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -13177,7 +13249,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -13197,7 +13269,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -13207,7 +13279,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -13216,7 +13288,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -13228,7 +13300,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -13243,7 +13315,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -13257,7 +13329,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -13292,7 +13364,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -13302,7 +13374,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -13323,7 +13395,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -13333,8 +13405,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -13383,7 +13837,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -13393,7 +13847,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -13403,7 +13857,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -13413,7 +13867,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -13425,7 +13879,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -13436,7 +13890,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -13445,7 +13899,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -13456,7 +13910,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -13492,7 +13946,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -13502,7 +13956,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -13536,7 +13990,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -13562,7 +14016,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -13591,7 +14045,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -13613,7 +14067,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -13623,7 +14077,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -13632,8 +14086,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -13645,19 +14111,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -13680,7 +14134,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -13691,7 +14145,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -13701,7 +14155,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -13712,7 +14166,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -13728,7 +14182,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -13763,7 +14217,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -13773,389 +14227,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -14175,7 +14247,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -14186,7 +14258,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -14203,7 +14275,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -14220,7 +14292,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -14230,7 +14302,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -14239,7 +14311,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -14248,7 +14320,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -14275,7 +14347,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -14350,7 +14422,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -14373,7 +14445,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -14388,7 +14460,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -14399,7 +14471,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -14429,7 +14501,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -14437,7 +14509,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -14447,7 +14519,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -14455,7 +14527,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -14463,7 +14535,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -14473,7 +14545,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -14481,7 +14553,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -14490,7 +14562,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -14508,7 +14580,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -14529,7 +14601,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -14546,7 +14618,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -14555,7 +14627,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -14574,7 +14646,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -14582,7 +14654,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -14602,7 +14674,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -14624,7 +14696,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -14633,7 +14705,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -14650,8 +14722,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -14679,157 +14901,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -14837,7 +14909,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -14847,7 +14919,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -14856,7 +14928,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -14872,7 +14944,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -14885,7 +14957,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -14908,7 +14980,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -14918,7 +14990,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -14928,7 +15000,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -14945,7 +15017,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -14954,7 +15026,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -14966,7 +15038,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -14977,7 +15049,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -14990,7 +15062,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -15000,17 +15072,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -15033,7 +15202,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -15042,7 +15211,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -15063,19 +15232,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -15084,7 +15262,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -15105,7 +15283,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -15114,7 +15292,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -15143,7 +15321,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -15152,7 +15330,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -15198,7 +15376,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -15207,7 +15385,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -15231,7 +15409,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -15256,7 +15434,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -15267,7 +15445,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -15284,7 +15462,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -15293,7 +15471,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -15303,112 +15481,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15418,7 +15905,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -15442,7 +15929,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -15452,7 +15939,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -15462,7 +15949,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -15472,7 +15959,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -15482,7 +15969,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -15492,7 +15979,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -15502,7 +15989,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -15512,7 +15999,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -15522,7 +16009,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -15532,7 +16019,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -15542,7 +16029,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -15552,7 +16039,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -15562,7 +16049,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -15575,7 +16062,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -15586,7 +16073,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -15615,7 +16102,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15625,7 +16112,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15635,7 +16122,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -15673,7 +16160,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -15689,7 +16176,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -15699,7 +16186,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -15713,7 +16200,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15760,7 +16247,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15783,7 +16270,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15794,7 +16281,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15825,7 +16312,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -15855,7 +16342,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -15870,7 +16357,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15895,7 +16382,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -15907,7 +16394,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15917,7 +16404,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15927,7 +16414,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15937,7 +16424,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15947,7 +16434,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15957,7 +16444,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15971,7 +16458,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -15982,7 +16469,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -15992,7 +16479,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -16003,7 +16490,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -16023,7 +16510,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -16036,7 +16523,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -16049,7 +16536,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -16065,7 +16552,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -16083,7 +16570,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -16094,7 +16581,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -16122,7 +16609,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -16141,7 +16628,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -16155,7 +16642,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -16165,7 +16652,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -16186,7 +16673,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -16203,7 +16690,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -16218,7 +16705,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -16254,7 +16741,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -16270,21 +16757,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -16298,8 +16771,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -16310,12 +16797,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -16323,13 +16810,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -16345,7 +16832,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -16370,7 +16857,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -16380,7 +16867,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -16389,7 +16876,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -16405,7 +16892,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -16438,7 +16925,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -16488,7 +16975,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -16503,7 +16990,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -16518,7 +17005,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -16526,7 +17013,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -16540,7 +17027,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -16554,7 +17041,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -16566,7 +17053,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -16578,7 +17065,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -16590,7 +17077,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -16602,7 +17089,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -16612,7 +17099,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -16622,7 +17109,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -16632,7 +17119,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -16641,7 +17128,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -16650,7 +17137,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -16660,7 +17147,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -16669,7 +17156,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -16678,7 +17165,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -16694,7 +17181,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -16704,7 +17191,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -16714,7 +17201,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -16731,7 +17218,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -16742,7 +17229,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -16758,7 +17245,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -16768,7 +17255,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -16778,7 +17265,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -16816,7 +17303,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -16831,7 +17318,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -16843,7 +17330,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -16859,8 +17346,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -16920,59 +17459,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -16982,7 +17469,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -16992,17 +17479,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -17029,7 +17506,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -17039,7 +17516,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -17064,7 +17541,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -17079,7 +17556,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -17089,7 +17566,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -17120,7 +17597,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -17138,8 +17615,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -17161,7 +17648,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -17172,7 +17659,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -17182,7 +17669,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -17195,420 +17682,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -17618,7 +17692,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -17629,7 +17703,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -17661,7 +17735,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -17670,7 +17744,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -17713,7 +17787,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -17737,7 +17811,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -17749,7 +17823,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -17767,7 +17841,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -17778,7 +17852,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -17794,7 +17868,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -17812,7 +17886,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -17823,7 +17897,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -17832,7 +17906,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -17843,7 +17917,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -17863,7 +17937,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -17874,8 +17948,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -17897,16 +17980,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -17924,7 +17998,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -17937,7 +18011,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -17951,7 +18025,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -17975,45 +18049,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -18023,7 +18059,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -18033,7 +18069,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -18045,8 +18081,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -18056,7 +18130,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -18064,7 +18138,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -18073,7 +18147,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -18081,7 +18155,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -18089,7 +18163,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -18097,7 +18171,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -18105,7 +18179,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -18366,13 +18440,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -18397,9 +18471,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -18429,18 +18503,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -18474,6 +18548,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -18506,23 +18594,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -18668,13 +18742,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -18699,9 +18773,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -18731,18 +18805,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -18776,6 +18850,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -18808,23 +18896,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -18848,7 +18922,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -18856,7 +18930,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -18867,7 +18941,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -18875,7 +18949,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -18883,7 +18957,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -18923,7 +18997,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -18932,7 +19006,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -18941,7 +19015,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -18954,7 +19028,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -18963,7 +19037,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -18973,7 +19047,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -18983,8 +19057,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -19020,7 +19104,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -19043,7 +19127,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -19071,6 +19155,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -19129,6 +19214,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -19142,8 +19231,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -19266,9 +19355,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -19324,7 +19413,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -19341,7 +19430,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -19351,7 +19440,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -19398,7 +19487,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -19408,7 +19497,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -19417,7 +19506,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -19428,7 +19517,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -19437,7 +19526,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -19446,7 +19535,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -19483,7 +19572,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -19499,17 +19588,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -19546,6 +19625,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -19554,81 +19708,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -19673,16 +19752,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -19907,38 +19986,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -20186,7 +20265,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -20236,8 +20315,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -20245,59 +20366,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -20385,48 +20464,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -20451,307 +20509,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -20759,8 +20577,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -20883,9 +20701,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -21004,6 +20822,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -21017,6 +20836,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -21024,12 +20849,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -21041,6 +20860,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -21048,9 +20875,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -21061,14 +20888,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index d285df3f4db..c3aff258d24 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -24,15 +24,15 @@ and limitations under the License. ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -45,32 +45,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -110,13 +110,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -130,15 +123,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -147,17 +140,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -167,9 +167,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -182,6 +181,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -194,17 +194,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -231,11 +231,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -260,39 +260,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -304,31 +418,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -346,8 +465,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -357,12 +476,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -370,35 +489,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -408,28 +527,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -447,13 +566,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -461,241 +580,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -704,39 +704,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -746,9 +746,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -757,14 +757,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -773,8 +773,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -784,38 +784,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -823,15 +848,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -846,19 +871,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -868,285 +893,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -1158,13 +1158,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -1173,11 +1173,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -1185,10 +1185,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -1207,19 +1207,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1235,8 +1222,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1246,7 +1246,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -1291,7 +1291,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -1304,7 +1304,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -1319,7 +1319,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -1342,7 +1342,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -1388,7 +1388,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -1397,7 +1397,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -1410,7 +1410,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -1429,7 +1429,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -1445,7 +1445,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -1456,7 +1456,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -1470,7 +1470,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -1493,7 +1493,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -1502,7 +1502,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -1511,13 +1511,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1525,7 +1525,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -1538,16 +1538,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -1560,7 +1849,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -1569,7 +1858,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1580,7 +1869,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -1591,7 +1880,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -1601,7 +1890,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1614,7 +1903,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -1623,7 +1912,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -1633,7 +1922,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -1645,7 +1934,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -1655,8 +1944,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1672,8 +1961,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1681,7 +1970,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -1692,13 +1981,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -1774,9 +2063,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -1846,24 +2135,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -1999,9 +2288,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2053,7 +2342,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -2064,7 +2353,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -2090,7 +2379,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -2098,296 +2387,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -2397,150 +2397,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -2551,7 +2408,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -2568,7 +2425,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -2581,7 +2438,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -2595,7 +2452,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -2608,7 +2465,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -2617,7 +2474,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -2628,7 +2485,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -2637,7 +2494,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -2650,7 +2507,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -2663,7 +2520,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -2674,7 +2531,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -2769,299 +2626,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -3081,146 +2930,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -3229,243 +3086,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3474,7 +3331,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -3483,7 +3340,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -3497,8 +3354,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -3508,7 +3508,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -3522,27 +3522,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -3623,9 +3603,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -3643,18 +3623,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -3665,9 +3645,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3676,7 +3656,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -3690,12 +3670,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -3722,7 +3702,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -3733,8 +3713,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -3748,7 +3748,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -3756,7 +3756,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -3767,7 +3767,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -3778,7 +3778,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -3793,7 +3793,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -3803,7 +3803,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -3817,7 +3817,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -3831,7 +3831,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -3840,7 +3840,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -3855,7 +3855,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -3865,7 +3865,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -3874,7 +3874,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -3885,8 +3885,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -3897,87 +3937,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3986,70 +4026,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -4060,66 +4100,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4128,7 +4168,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -4136,7 +4176,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4146,30 +4186,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4178,16 +4204,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4196,7 +4222,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4255,71 +4281,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4328,32 +4368,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4363,42 +4403,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -4409,7 +4438,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -4420,7 +4449,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -4431,16 +4460,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4449,8 +4478,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4459,7 +4499,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -4632,54 +4672,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4688,39 +4728,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4729,12 +4769,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4743,7 +4783,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -4752,74 +4792,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4829,7 +4869,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -4837,68 +4877,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4907,7 +4947,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4934,33 +4974,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -4976,8 +5016,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4986,29 +5026,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -5019,12 +5037,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5033,12 +5051,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5047,7 +5087,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -5055,79 +5095,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5136,86 +5176,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -5227,210 +5267,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5439,31 +5479,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5472,16 +5497,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5490,41 +5515,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -5535,16 +5575,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5553,7 +5593,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -5585,7 +5625,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -5594,162 +5634,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -5776,7 +5816,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -5788,32 +5828,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5822,7 +5862,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -5838,16 +5878,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5856,13 +5896,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -5872,154 +6029,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6028,37 +6068,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6067,7 +6107,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -6079,7 +6119,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -6101,12 +6141,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6116,24 +6156,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6142,7 +6182,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6152,12 +6192,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6166,24 +6206,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6192,12 +6232,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6206,38 +6246,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6247,94 +6287,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6344,18 +6384,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -6369,7 +6409,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6379,17 +6419,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6398,16 +6438,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6416,53 +6456,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6471,20 +6511,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6493,7 +6533,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6503,111 +6543,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6616,12 +6656,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6630,39 +6670,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6671,26 +6711,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6699,7 +6739,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -6710,105 +6750,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6817,7 +6857,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -6828,12 +6868,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6842,7 +6882,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -6867,7 +6907,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -6879,7 +6919,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6889,7 +6929,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -6899,8 +6939,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -6912,31 +6952,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6944,47 +6984,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -7008,7 +7008,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -7017,7 +7017,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -7034,7 +7034,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7043,7 +7043,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -7054,7 +7054,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -7065,14 +7065,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -7088,7 +7088,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -7104,14 +7104,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -7128,7 +7128,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -7136,7 +7136,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -7150,7 +7150,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -7160,7 +7160,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -7180,7 +7180,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -7190,7 +7190,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -7199,7 +7199,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -7211,7 +7211,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -7226,7 +7226,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -7240,7 +7240,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -7275,7 +7275,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -7285,7 +7285,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -7306,7 +7306,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -7316,8 +7316,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -7366,7 +7748,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -7376,7 +7758,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -7386,7 +7768,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -7396,7 +7778,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -7408,7 +7790,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -7419,7 +7801,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -7428,7 +7810,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -7439,7 +7821,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -7475,7 +7857,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -7485,7 +7867,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -7519,7 +7901,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -7545,7 +7927,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -7574,7 +7956,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -7596,7 +7978,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -7606,7 +7988,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -7615,8 +7997,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -7628,19 +8022,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -7663,7 +8045,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -7674,7 +8056,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -7684,7 +8066,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -7695,7 +8077,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -7711,7 +8093,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -7746,7 +8128,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -7756,389 +8138,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -8158,7 +8158,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -8169,7 +8169,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -8186,7 +8186,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -8203,7 +8203,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -8213,7 +8213,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -8222,7 +8222,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -8231,7 +8231,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -8258,7 +8258,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -8333,7 +8333,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -8356,7 +8356,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -8371,7 +8371,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -8382,7 +8382,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -8412,7 +8412,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -8420,7 +8420,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -8430,7 +8430,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -8438,7 +8438,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -8446,7 +8446,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -8456,7 +8456,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -8464,7 +8464,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -8473,7 +8473,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -8491,7 +8491,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -8512,7 +8512,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -8529,7 +8529,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -8538,7 +8538,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -8557,7 +8557,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -8565,7 +8565,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -8585,7 +8585,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -8607,7 +8607,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -8616,7 +8616,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -8633,8 +8633,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -8662,157 +8812,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -8820,7 +8820,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -8830,7 +8830,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -8839,7 +8839,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -8855,7 +8855,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -8868,7 +8868,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -8891,7 +8891,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -8901,7 +8901,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -8911,7 +8911,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -8928,7 +8928,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -8937,7 +8937,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -8949,7 +8949,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -8960,7 +8960,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -8973,7 +8973,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -8983,17 +8983,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -9016,7 +9113,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -9025,7 +9122,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -9046,19 +9143,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -9067,7 +9173,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -9088,7 +9194,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -9097,7 +9203,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -9126,7 +9232,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -9135,7 +9241,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -9181,7 +9287,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -9190,7 +9296,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -9214,7 +9320,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -9239,7 +9345,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -9250,7 +9356,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -9267,7 +9373,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -9276,7 +9382,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -9286,112 +9392,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9401,7 +9816,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -9425,7 +9840,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -9435,7 +9850,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -9445,7 +9860,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -9455,7 +9870,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -9465,7 +9880,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -9475,7 +9890,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -9485,7 +9900,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -9495,7 +9910,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -9505,7 +9920,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -9515,7 +9930,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -9525,7 +9940,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -9535,7 +9950,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -9545,7 +9960,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9558,7 +9973,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -9569,7 +9984,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -9598,7 +10013,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9608,7 +10023,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9618,7 +10033,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -9656,7 +10071,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -9672,7 +10087,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -9682,7 +10097,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9696,7 +10111,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9743,7 +10158,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9766,7 +10181,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9777,7 +10192,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9808,7 +10223,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -9838,7 +10253,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -9853,7 +10268,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9878,7 +10293,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -9890,7 +10305,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9900,7 +10315,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9910,7 +10325,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9920,7 +10335,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9930,7 +10345,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9940,7 +10355,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9954,7 +10369,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -9965,7 +10380,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9975,7 +10390,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -9986,7 +10401,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10006,7 +10421,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -10019,7 +10434,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -10032,7 +10447,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10048,7 +10463,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -10066,7 +10481,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10077,7 +10492,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -10105,7 +10520,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -10124,7 +10539,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10138,7 +10553,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10148,7 +10563,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -10169,7 +10584,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -10186,7 +10601,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10201,7 +10616,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -10237,7 +10652,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -10253,21 +10668,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -10281,8 +10682,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -10293,12 +10708,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10306,13 +10721,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -10328,7 +10743,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -10353,7 +10768,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10363,7 +10778,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -10372,7 +10787,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -10388,7 +10803,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -10421,7 +10836,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -10471,7 +10886,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -10486,7 +10901,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -10501,7 +10916,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -10509,7 +10924,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -10523,7 +10938,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -10537,7 +10952,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -10549,7 +10964,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -10561,7 +10976,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -10573,7 +10988,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -10585,7 +11000,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -10595,7 +11010,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -10605,7 +11020,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -10615,7 +11030,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -10624,7 +11039,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -10633,7 +11048,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -10643,7 +11058,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -10652,7 +11067,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -10661,7 +11076,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -10677,7 +11092,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -10687,7 +11102,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -10697,7 +11112,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10714,7 +11129,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -10725,7 +11140,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -10741,7 +11156,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10751,7 +11166,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10761,7 +11176,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -10799,7 +11214,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -10814,7 +11229,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -10826,7 +11241,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10842,8 +11257,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -10903,59 +11370,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10965,7 +11380,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10975,17 +11390,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -11012,7 +11417,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11022,7 +11427,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -11047,7 +11452,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -11062,7 +11467,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11072,7 +11477,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -11103,7 +11508,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -11121,8 +11526,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11144,7 +11559,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -11155,7 +11570,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -11165,7 +11580,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -11178,420 +11593,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -11601,7 +11603,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -11612,7 +11614,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -11644,7 +11646,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -11653,7 +11655,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -11696,7 +11698,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -11720,7 +11722,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -11732,7 +11734,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -11750,7 +11752,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -11761,7 +11763,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -11777,7 +11779,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -11795,7 +11797,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -11806,7 +11808,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -11815,7 +11817,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -11826,7 +11828,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -11846,7 +11848,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -11857,8 +11859,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -11880,16 +11891,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -11907,7 +11909,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -11920,7 +11922,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -11934,7 +11936,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -11958,45 +11960,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -12006,7 +11970,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -12016,7 +11980,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -12028,8 +11992,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -12039,7 +12041,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -12047,7 +12049,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -12056,7 +12058,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -12064,7 +12066,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -12072,7 +12074,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -12080,7 +12082,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -12088,7 +12090,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -12349,13 +12351,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12380,9 +12382,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12412,18 +12414,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12457,6 +12459,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12489,23 +12505,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12651,13 +12653,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12682,9 +12684,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12714,18 +12716,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12759,6 +12761,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12791,23 +12807,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12831,7 +12833,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -12839,7 +12841,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -12850,7 +12852,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -12858,7 +12860,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -12866,7 +12868,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -12906,7 +12908,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -12915,7 +12917,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -12924,7 +12926,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -12937,7 +12939,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -12946,7 +12948,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -12956,7 +12958,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -12966,8 +12968,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -13003,7 +13015,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -13026,7 +13038,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -13054,6 +13066,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -13112,6 +13125,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -13125,8 +13142,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13249,9 +13266,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13307,7 +13324,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -13324,7 +13341,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -13334,7 +13351,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -13381,7 +13398,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -13391,7 +13408,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -13400,7 +13417,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -13411,7 +13428,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -13420,7 +13437,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -13429,7 +13446,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -13466,7 +13483,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -13482,17 +13499,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -13529,6 +13536,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -13537,81 +13619,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -13656,16 +13663,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -13890,38 +13897,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -14169,7 +14176,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -14219,8 +14226,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -14228,59 +14277,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -14368,48 +14375,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -14434,307 +14420,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -14742,8 +14488,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -14866,9 +14612,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -14987,6 +14733,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -15000,6 +14747,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -15007,12 +14760,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -15024,6 +14771,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -15031,9 +14786,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -15044,14 +14799,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 4e7672f7973..997b007a879 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -20,7 +20,7 @@ and limitations under the License. ///////////////////////////// -/// IE Worker APIs +/// Worker APIs ///////////////////////////// interface Algorithm { @@ -28,16 +28,16 @@ interface Algorithm { } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface EventInit { @@ -69,16 +69,16 @@ interface MessageEventInit extends EventInit { channel?: string; data?: any; origin?: string; - source?: any; ports?: MessagePort[]; + source?: any; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -86,29 +86,29 @@ interface ObjectURLOptions { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; } interface RequestInit { - method?: string; - headers?: any; body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; cache?: RequestCache; - redirect?: RequestRedirect; + credentials?: RequestCredentials; + headers?: any; integrity?: string; keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; window?: any; } interface ResponseInit { + headers?: any; status?: number; statusText?: string; - headers?: any; } interface ClientQueryOptions { @@ -176,7 +176,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface Blob { readonly size: number; @@ -189,7 +189,7 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} +}; interface Cache { add(request: RequestInfo): Promise; @@ -204,7 +204,7 @@ interface Cache { declare var Cache: { prototype: Cache; new(): Cache; -} +}; interface CacheStorage { delete(cacheName: string): Promise; @@ -217,7 +217,7 @@ interface CacheStorage { declare var CacheStorage: { prototype: CacheStorage; new(): CacheStorage; -} +}; interface CloseEvent extends Event { readonly code: number; @@ -229,7 +229,7 @@ interface CloseEvent extends Event { declare var CloseEvent: { prototype: CloseEvent; new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} +}; interface Console { assert(test?: boolean, message?: string, ...optionalParams: any[]): void; @@ -240,8 +240,8 @@ interface Console { dirxml(value: any): void; error(message?: any, ...optionalParams: any[]): void; exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; groupEnd(): void; info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; @@ -259,7 +259,7 @@ interface Console { declare var Console: { prototype: Console; new(): Console; -} +}; interface Coordinates { readonly accuracy: number; @@ -274,7 +274,7 @@ interface Coordinates { declare var Coordinates: { prototype: Coordinates; new(): Coordinates; -} +}; interface CryptoKey { readonly algorithm: KeyAlgorithm; @@ -286,7 +286,7 @@ interface CryptoKey { declare var CryptoKey: { prototype: CryptoKey; new(): CryptoKey; -} +}; interface DOMError { readonly name: string; @@ -296,7 +296,7 @@ interface DOMError { declare var DOMError: { prototype: DOMError; new(): DOMError; -} +}; interface DOMException { readonly code: number; @@ -316,10 +316,10 @@ interface DOMException { readonly INVALID_STATE_ERR: number; readonly NAMESPACE_ERR: number; readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; readonly NO_DATA_ALLOWED_ERR: number; readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -348,10 +348,10 @@ declare var DOMException: { readonly INVALID_STATE_ERR: number; readonly NAMESPACE_ERR: number; readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; readonly NO_DATA_ALLOWED_ERR: number; readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -362,7 +362,7 @@ declare var DOMException: { readonly URL_MISMATCH_ERR: number; readonly VALIDATION_ERR: number; readonly WRONG_DOCUMENT_ERR: number; -} +}; interface DOMStringList { readonly length: number; @@ -374,7 +374,7 @@ interface DOMStringList { declare var DOMStringList: { prototype: DOMStringList; new(): DOMStringList; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -388,12 +388,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -420,7 +420,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -431,7 +431,7 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -442,7 +442,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -453,7 +453,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -468,8 +468,17 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; +}; + +interface FormData { + append(name: string, value: string | Blob, fileName?: string): void; } +declare var FormData: { + prototype: FormData; + new(): FormData; +}; + interface Headers { append(name: string, value: string): void; delete(name: string): void; @@ -482,7 +491,7 @@ interface Headers { declare var Headers: { prototype: Headers; new(init?: any): Headers; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -506,7 +515,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -515,7 +524,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -532,7 +541,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -541,7 +550,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -552,7 +561,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -563,14 +572,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -586,7 +595,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -602,14 +611,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -626,7 +635,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -634,7 +643,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -648,7 +657,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -658,7 +667,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -678,7 +687,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -688,7 +697,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -700,7 +709,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface MessageChannel { readonly port1: MessagePort; @@ -710,7 +719,7 @@ interface MessageChannel { declare var MessageChannel: { prototype: MessageChannel; new(): MessageChannel; -} +}; interface MessageEvent extends Event { readonly data: any; @@ -723,7 +732,7 @@ interface MessageEvent extends Event { declare var MessageEvent: { prototype: MessageEvent; new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} +}; interface MessagePortEventMap { "message": MessageEvent; @@ -741,7 +750,7 @@ interface MessagePort extends EventTarget { declare var MessagePort: { prototype: MessagePort; new(): MessagePort; -} +}; interface NotificationEventMap { "click": Event; @@ -771,7 +780,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface Performance { readonly navigation: PerformanceNavigation; @@ -794,7 +803,7 @@ interface Performance { declare var Performance: { prototype: Performance; new(): Performance; -} +}; interface PerformanceNavigation { readonly redirectCount: number; @@ -813,18 +822,18 @@ declare var PerformanceNavigation: { readonly TYPE_NAVIGATE: number; readonly TYPE_RELOAD: number; readonly TYPE_RESERVED: number; -} +}; interface PerformanceTiming { readonly connectEnd: number; readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -844,7 +853,7 @@ interface PerformanceTiming { declare var PerformanceTiming: { prototype: PerformanceTiming; new(): PerformanceTiming; -} +}; interface Position { readonly coords: Coordinates; @@ -854,7 +863,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -871,7 +880,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -883,7 +892,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -894,7 +903,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -907,7 +916,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -917,7 +926,7 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; -} +}; interface ReadableStream { readonly locked: boolean; @@ -928,7 +937,7 @@ interface ReadableStream { declare var ReadableStream: { prototype: ReadableStream; new(): ReadableStream; -} +}; interface ReadableStreamReader { cancel(): Promise; @@ -939,7 +948,7 @@ interface ReadableStreamReader { declare var ReadableStreamReader: { prototype: ReadableStreamReader; new(): ReadableStreamReader; -} +}; interface Request extends Object, Body { readonly cache: RequestCache; @@ -961,7 +970,7 @@ interface Request extends Object, Body { declare var Request: { prototype: Request; new(input: Request | string, init?: RequestInit): Request; -} +}; interface Response extends Object, Body { readonly body: ReadableStream | null; @@ -977,7 +986,9 @@ interface Response extends Object, Body { declare var Response: { prototype: Response; new(body?: any, init?: ResponseInit): Response; -} + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; interface ServiceWorkerEventMap extends AbstractWorkerEventMap { "statechange": Event; @@ -995,7 +1006,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker { declare var ServiceWorker: { prototype: ServiceWorker; new(): ServiceWorker; -} +}; interface ServiceWorkerRegistrationEventMap { "updatefound": Event; @@ -1020,7 +1031,7 @@ interface ServiceWorkerRegistration extends EventTarget { declare var ServiceWorkerRegistration: { prototype: ServiceWorkerRegistration; new(): ServiceWorkerRegistration; -} +}; interface SyncManager { getTags(): any; @@ -1030,7 +1041,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface URL { hash: string; @@ -1053,7 +1064,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} +}; interface WebSocketEventMap { "close": CloseEvent; @@ -1090,7 +1101,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -1107,7 +1118,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -1153,7 +1164,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -1163,7 +1174,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -1278,7 +1289,7 @@ interface Client { declare var Client: { prototype: Client; new(): Client; -} +}; interface Clients { claim(): Promise; @@ -1290,7 +1301,7 @@ interface Clients { declare var Clients: { prototype: Clients; new(): Clients; -} +}; interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "message": MessageEvent; @@ -1307,7 +1318,7 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { declare var DedicatedWorkerGlobalScope: { prototype: DedicatedWorkerGlobalScope; new(): DedicatedWorkerGlobalScope; -} +}; interface ExtendableEvent extends Event { waitUntil(f: Promise): void; @@ -1316,7 +1327,7 @@ interface ExtendableEvent extends Event { declare var ExtendableEvent: { prototype: ExtendableEvent; new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent; -} +}; interface ExtendableMessageEvent extends ExtendableEvent { readonly data: any; @@ -1329,7 +1340,7 @@ interface ExtendableMessageEvent extends ExtendableEvent { declare var ExtendableMessageEvent: { prototype: ExtendableMessageEvent; new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent; -} +}; interface FetchEvent extends ExtendableEvent { readonly clientId: string | null; @@ -1341,7 +1352,7 @@ interface FetchEvent extends ExtendableEvent { declare var FetchEvent: { prototype: FetchEvent; new(type: string, eventInitDict: FetchEventInit): FetchEvent; -} +}; interface FileReaderSync { readAsArrayBuffer(blob: Blob): any; @@ -1353,7 +1364,7 @@ interface FileReaderSync { declare var FileReaderSync: { prototype: FileReaderSync; new(): FileReaderSync; -} +}; interface NotificationEvent extends ExtendableEvent { readonly action: string; @@ -1363,7 +1374,7 @@ interface NotificationEvent extends ExtendableEvent { declare var NotificationEvent: { prototype: NotificationEvent; new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; -} +}; interface PushEvent extends ExtendableEvent { readonly data: PushMessageData | null; @@ -1372,7 +1383,7 @@ interface PushEvent extends ExtendableEvent { declare var PushEvent: { prototype: PushEvent; new(type: string, eventInitDict?: PushEventInit): PushEvent; -} +}; interface PushMessageData { arrayBuffer(): ArrayBuffer; @@ -1384,7 +1395,7 @@ interface PushMessageData { declare var PushMessageData: { prototype: PushMessageData; new(): PushMessageData; -} +}; interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "activate": ExtendableEvent; @@ -1418,7 +1429,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { declare var ServiceWorkerGlobalScope: { prototype: ServiceWorkerGlobalScope; new(): ServiceWorkerGlobalScope; -} +}; interface SyncEvent extends ExtendableEvent { readonly lastChance: boolean; @@ -1428,7 +1439,7 @@ interface SyncEvent extends ExtendableEvent { declare var SyncEvent: { prototype: SyncEvent; new(type: string, init: SyncEventInit): SyncEvent; -} +}; interface WindowClient extends Client { readonly focused: boolean; @@ -1440,7 +1451,7 @@ interface WindowClient extends Client { declare var WindowClient: { prototype: WindowClient; new(): WindowClient; -} +}; interface WorkerGlobalScopeEventMap { "error": ErrorEvent; @@ -1463,7 +1474,7 @@ interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, Glo declare var WorkerGlobalScope: { prototype: WorkerGlobalScope; new(): WorkerGlobalScope; -} +}; interface WorkerLocation { readonly hash: string; @@ -1481,7 +1492,7 @@ interface WorkerLocation { declare var WorkerLocation: { prototype: WorkerLocation; new(): WorkerLocation; -} +}; interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware { readonly hardwareConcurrency: number; @@ -1490,7 +1501,7 @@ interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, Navigato declare var WorkerNavigator: { prototype: WorkerNavigator; new(): WorkerNavigator; -} +}; interface WorkerUtils extends Object, WindowBase64 { readonly indexedDB: IDBFactory; @@ -1533,38 +1544,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface BlobPropertyBag { type?: string; @@ -1771,8 +1782,23 @@ interface AddEventListenerOptions extends EventListenerOptions { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -1780,21 +1806,6 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface FunctionStringCallback { - (data: string): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any; declare function close(): void; declare function postMessage(message: any, transfer?: any[]): void; diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 9e26197e21d..7390c59bfbc 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -47,6 +47,9 @@ declare namespace ts.server.protocol { type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; type GetCodeFixes = "getCodeFixes"; type GetSupportedCodeFixes = "getSupportedCodeFixes"; + type GetApplicableRefactors = "getApplicableRefactors"; + type GetRefactorCodeActions = "getRefactorCodeActions"; + type GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; } /** * A TypeScript Server message @@ -287,6 +290,33 @@ declare namespace ts.server.protocol { */ offset: number; } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + interface ApplicableRefactorInfo { + name: string; + description: string; + } + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + interface GetRefactorCodeActionsRequest extends Request { + command: CommandTypes.GetRefactorCodeActions; + arguments: GetRefactorCodeActionsRequestArgs; + } + type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & { + refactorName: string; + }; + type RefactorCodeActions = { + actions: protocol.CodeAction[]; + renameLocation?: number; + }; + interface GetRefactorCodeActionsResponse extends Response { + body: RefactorCodeActions; + } /** * Request for the available codefixes at a specific position. */ @@ -294,10 +324,7 @@ declare namespace ts.server.protocol { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } - /** - * Instances of this interface specify errorcodes on a specific location in a sourcefile. - */ - interface CodeFixRequestArgs extends FileRequestArgs { + interface FileRangeRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). */ @@ -314,6 +341,11 @@ declare namespace ts.server.protocol { * The character offset (on the line) for the request (1-based). */ endOffset: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRangeRequestArgs { /** * Errorcodes we want to get the fixes for. */ @@ -1782,6 +1814,7 @@ declare namespace ts.server.protocol { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; diff --git a/lib/tsc.js b/lib/tsc.js index 693a32dc98b..9fb3135736f 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -30,12 +30,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { @@ -315,6 +323,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -519,6 +536,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1543,6 +1582,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -2579,6 +2622,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2686,7 +2730,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -2881,6 +2925,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3176,6 +3228,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -3221,6 +3274,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3302,6 +3357,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -3850,9 +3908,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -4982,9 +5041,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -5141,26 +5198,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5367,10 +5426,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -5622,6 +5677,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -5846,6 +5910,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -6252,9 +6320,6 @@ var ts; } ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } var func = param.parent; var tags = getJSDocTags(func, 286); if (!param.name) { @@ -6273,6 +6338,18 @@ var ts; } } ts.getJSDocParameterTags = getJSDocParameterTags; + function getParameterFromJSDoc(node) { + var name = node.parameterName.text; + var grandParent = node.parent.parent; + ts.Debug.assert(node.parent.kind === 283); + if (!isFunctionLike(grandParent)) { + return undefined; + } + return ts.find(grandParent.parameters, function (p) { + return p.name.kind === 71 && p.name.text === name; + }); + } + ts.getParameterFromJSDoc = getParameterFromJSDoc; function getJSDocType(node) { var tag = getFirstJSDocTag(node, 288); if (!tag && node.kind === 146) { @@ -6393,19 +6470,14 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { @@ -6507,21 +6579,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -6545,6 +6615,9 @@ var ts; } ts.isTrivia = isTrivia; function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6589,7 +6662,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -6859,6 +6933,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -6962,12 +7038,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -7056,7 +7133,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -7108,7 +7185,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -7597,13 +7674,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -7851,10 +7928,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -7922,9 +7995,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -8122,6 +8206,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8208,6 +8293,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -8230,6 +8319,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -8301,8 +8394,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8418,6 +8511,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -8677,6 +8812,27 @@ var ts; return identifier.length >= 3 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 && identifier.charCodeAt(2) === 95 ? identifier.substr(1) : identifier; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; })(ts || (ts = {})); var ts; (function (ts) { @@ -8756,15 +8912,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -8852,237 +9017,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -9093,42 +9033,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -9165,6 +9069,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -9186,7 +9110,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -9199,7 +9140,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -9209,7 +9150,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -9277,6 +9218,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -9322,9 +9506,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -9337,9 +9520,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -9387,9 +9569,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -9579,10 +9761,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -9709,6 +9891,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -9723,6 +9918,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -9732,7 +9931,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -9752,35 +9951,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -9999,6 +10169,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -10047,6 +10250,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -10067,7 +10312,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -10108,6 +10353,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -10138,7 +10395,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -10324,19 +10582,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -10351,6 +10596,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -10376,20 +10633,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -10398,10 +10641,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -10411,12 +10654,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -10425,10 +10680,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -10440,10 +10695,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -10454,10 +10709,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -10467,10 +10722,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -10565,14 +10819,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -10593,6 +10847,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -10903,6 +11180,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -11143,7 +11439,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -11250,9 +11548,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -11363,16 +11662,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -11541,6 +11830,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -11686,7 +12003,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -12343,6 +12660,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -16642,6 +16961,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -17380,7 +17701,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -17408,7 +17729,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -17441,19 +17762,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -17471,15 +17793,8 @@ var ts; case 243: return node.isExportEquals ? "export=" : "default"; case 194: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2: - return "export="; - case 1: - case 4: - case 5: - return node.left.name.text; - case 3: - return node.left.expression.name.text; + if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; @@ -17549,9 +17864,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -17571,6 +17886,8 @@ var ts; } } else { + if (node.kind === 290) + ts.Debug.assert(ts.isInJavaScriptFile(node)); var isJSDocTypedefInJSDocNamespace = node.kind === 290 && node.name && node.name.kind === 71 && @@ -17700,9 +18017,7 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } + ts.forEach(node.jsDoc, bind); if (checkUnreachable(node)) { bindEachChild(node); return; @@ -18747,9 +19062,7 @@ var ts; } node.parent = parent; var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } + bindJSDocTypedefTagIfAny(node); bindWorker(node); if (node.kind > 142) { var saveParent = parent; @@ -18809,7 +19122,7 @@ var ts; function bindWorker(node) { switch (node.kind) { case 71: - if (node.isInJSDocNamespace) { + if (ts.isInJavaScriptFile(node) && node.isInJSDocNamespace) { var parentNode = node.parent; while (parentNode && parentNode.kind !== 290) { parentNode = parentNode.parent; @@ -18877,10 +19190,7 @@ var ts; return bindVariableDeclarationOrBindingElement(node); case 149: case 148: - case 276: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); - case 291: - return bindJSDocProperty(node); + return bindPropertyWorker(node); case 261: case 262: return bindPropertyOrMethodOrAccessor(node, 4, 0); @@ -18918,13 +19228,10 @@ var ts; return bindPropertyOrMethodOrAccessor(node, 65536, 74687); case 160: case 161: - case 279: return bindFunctionOrConstructorType(node); case 163: case 172: - case 292: - case 275: - return bindAnonymousDeclaration(node, 2048, "__type"); + return bindAnonymousTypeWorker(node); case 178: return bindObjectLiteralExpression(node); case 186: @@ -18941,11 +19248,6 @@ var ts; return bindClassLikeDeclaration(node); case 230: return bindBlockScopedDeclaration(node, 64, 792968); - case 290: - if (!node.fullName || node.fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); - } - break; case 231: return bindBlockScopedDeclaration(node, 524288, 793064); case 232: @@ -18978,8 +19280,37 @@ var ts; } case 234: return updateStrictModeStatementList(node.statements); + default: + if (ts.isInJavaScriptFile(node)) + return bindJSDocWorker(node); } } + function bindJSDocWorker(node) { + switch (node.kind) { + case 276: + return bindPropertyWorker(node); + case 291: + return declareSymbolAndAddToSymbolTable(node, 4, 0); + case 279: + return bindFunctionOrConstructorType(node); + case 292: + case 275: + return bindAnonymousTypeWorker(node); + case 290: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048, "__type"); + } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; if (parameterName && parameterName.kind === 71) { @@ -19196,7 +19527,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -19211,7 +19542,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19226,7 +19557,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -19239,10 +19570,8 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { node.flowNode = currentFlow; @@ -19251,9 +19580,6 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4, 0); - } function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); @@ -19965,12 +20291,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -20254,6 +20579,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -20387,12 +20714,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -20422,7 +20755,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -20741,6 +21073,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -20885,13 +21218,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -20964,11 +21300,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -21152,16 +21490,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -21234,9 +21572,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -21244,7 +21579,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -21272,7 +21607,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -21347,7 +21683,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -21356,7 +21696,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -21403,12 +21743,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -21417,7 +21757,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -21426,7 +21766,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -21448,7 +21788,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -21495,7 +21835,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -21505,7 +21845,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -21602,6 +21952,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -21633,13 +21987,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -21651,7 +22005,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -21754,10 +22108,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -21773,7 +22127,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -21895,7 +22249,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -21915,6 +22269,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -21974,7 +22333,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -22115,7 +22473,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -22385,34 +22743,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -22422,12 +22805,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -22444,23 +22827,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -22480,8 +22865,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -22492,72 +22877,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -22565,12 +22931,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -22612,41 +22978,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -22654,7 +23031,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -22664,48 +23041,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -22714,74 +23115,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -22789,18 +23237,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -22809,20 +23257,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -22848,28 +23286,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -22887,12 +23326,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -22928,13 +23369,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -22977,7 +23419,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -23042,12 +23484,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -23384,7 +23829,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -23635,10 +24080,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -23759,7 +24201,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -23859,7 +24301,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -23937,6 +24379,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -23953,16 +24396,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -24172,7 +24622,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -24228,7 +24678,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -24404,11 +24854,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -24572,77 +25023,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -24874,7 +25328,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -24951,8 +25405,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -25096,7 +25550,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -25216,6 +25670,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -25272,8 +25747,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -25315,7 +25790,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -25329,12 +25804,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -25400,7 +25875,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -25763,8 +26238,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -25891,8 +26367,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -25922,7 +26398,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -25934,7 +26410,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -25954,7 +26430,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -25966,7 +26442,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -26003,14 +26478,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -26069,16 +26545,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -26300,14 +26776,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -26315,8 +26791,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -26437,8 +26913,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -26489,9 +26965,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -26521,12 +26997,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -26541,11 +27017,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -26570,7 +27046,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -26702,7 +27178,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -26719,11 +27195,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -26750,15 +27226,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -26769,11 +27246,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -27028,7 +27507,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -27439,29 +27918,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -27472,42 +27949,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -27691,24 +28173,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -28057,10 +28521,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -28157,23 +28621,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -28284,7 +28759,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -28307,11 +28782,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -28350,8 +28825,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -28429,8 +28904,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -28438,8 +28913,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -28462,7 +28937,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -28502,27 +28977,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -28530,43 +29005,43 @@ 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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -28711,7 +29186,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -28788,7 +29263,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -28821,20 +29296,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -28847,7 +29312,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -28935,26 +29400,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -29037,8 +29501,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -29113,7 +29577,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -29123,7 +29587,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -29188,7 +29652,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -29248,8 +29712,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -29265,15 +29729,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -29475,7 +29940,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -29498,8 +29963,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -29568,8 +30033,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -29595,7 +30060,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -29621,7 +30086,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -29741,7 +30206,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -30174,6 +30639,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -30228,7 +30709,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -30258,12 +30739,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -30958,8 +31439,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -31050,7 +31531,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -31065,7 +31546,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -31203,6 +31684,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -31262,6 +31745,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -31279,6 +31766,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -31288,37 +31778,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -31328,9 +31818,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -31340,11 +31829,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -31399,7 +31892,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -31433,6 +31937,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -31442,6 +31960,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -31467,6 +31986,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -31512,7 +32032,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -31670,6 +32190,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -31681,7 +32219,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -31699,36 +32246,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -31803,42 +32332,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -31874,7 +32367,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -31890,6 +32383,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -31997,7 +32591,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -32020,8 +32620,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -32108,7 +32708,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -32344,7 +32944,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -32422,7 +33022,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -32450,7 +33050,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -32491,25 +33091,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -32519,14 +33150,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -32657,7 +33280,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -32784,8 +33407,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -32929,7 +33552,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -32993,10 +33616,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -33280,15 +33903,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -33368,7 +33991,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -33411,8 +34034,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33426,8 +34049,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -33436,8 +34059,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -33472,7 +34095,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -33744,7 +34367,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -33798,7 +34421,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -33880,12 +34503,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -33925,9 +34548,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -33981,7 +34604,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -34278,17 +34901,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -34311,7 +34931,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -34425,7 +35045,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -34499,7 +35119,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -34637,7 +35258,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -34676,7 +35297,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -34726,16 +35347,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -34746,7 +35367,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -34854,7 +35475,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -34867,8 +35488,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -34917,11 +35538,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -35117,7 +35739,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -35127,6 +35751,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -35153,7 +35814,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -35162,15 +35823,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -35283,15 +35944,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -35369,7 +36031,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -35431,7 +36093,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -35445,7 +36107,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -35641,7 +36303,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -35747,11 +36409,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -36201,11 +36864,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -36420,7 +37086,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -36439,7 +37105,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -36454,13 +37120,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -36479,7 +37142,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -36562,88 +37225,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -36656,75 +37312,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -36747,7 +37381,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -36972,6 +37606,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -37574,6 +38211,10 @@ var ts; return entityNameSymbol; } } + if (entityName.parent.kind === 286) { + var parameter = ts.getParameterFromJSDoc(entityName.parent); + return parameter && parameter.symbol; + } if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; @@ -37618,7 +38259,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -37731,7 +38372,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -37793,16 +38434,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -38063,7 +38704,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -38091,7 +38732,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -38103,15 +38744,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -38190,7 +38822,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -38337,7 +38968,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -38364,9 +38995,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -39395,6 +40027,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -39505,49 +40148,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -39558,20 +40211,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -39608,12 +40247,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -39630,6 +40269,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -39674,6 +40315,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -39682,6 +40327,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -39706,8 +40353,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -39716,6 +40361,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -39740,6 +40387,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -39795,6 +40444,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -40133,6 +40789,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -40572,7 +41231,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -41361,15 +42020,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -41656,7 +42310,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -41703,9 +42362,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -41838,7 +42497,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -42144,7 +42803,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -42385,7 +43044,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -42453,19 +43112,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -42592,6 +43246,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -42599,19 +43256,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -42620,12 +43275,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -42857,12 +43507,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -42874,11 +43534,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -42897,7 +43557,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -43335,7 +43995,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -43408,7 +44068,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -44271,12 +44931,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -45164,7 +45825,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -45357,8 +46018,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -46974,7 +47634,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -47137,9 +47797,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -47643,9 +48303,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -48158,9 +48816,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -48451,7 +49109,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -48554,7 +49212,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -48612,7 +49270,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -49387,7 +50045,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -49412,11 +50070,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -49820,8 +50478,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -49834,23 +50491,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -49860,12 +50524,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -49935,7 +50593,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50163,7 +50821,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -50260,7 +50918,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50272,12 +50930,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -50291,7 +50943,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -50306,6 +50958,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -50313,15 +50978,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -50342,7 +51014,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -50394,7 +51066,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -50402,7 +51075,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -50597,6 +51270,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -50855,7 +51533,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -51013,7 +51691,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -51044,7 +51722,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -51130,7 +51808,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -51206,7 +51886,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -51406,7 +52086,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -51426,7 +52106,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -51488,6 +52168,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -51513,6 +52195,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -51535,6 +52218,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -51649,7 +52333,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -51687,9 +52373,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -51700,8 +52392,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -51714,7 +52411,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -51790,7 +52487,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -51881,7 +52578,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -52560,6 +53257,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -52808,6 +53508,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -52985,7 +53694,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -53352,6 +54063,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -53401,6 +54189,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -53443,7 +54232,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -53492,7 +54282,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -53525,45 +54316,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -53572,15 +54382,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -53599,67 +54406,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -53667,11 +54480,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -53683,8 +54501,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -54024,7 +54841,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -54055,7 +54872,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -54096,13 +54912,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -54125,45 +54941,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -54299,10 +55120,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -54351,7 +55172,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -54448,12 +55269,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -55536,49 +56357,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -55588,37 +56388,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -55649,9 +56419,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -55668,9 +56435,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -55915,8 +56739,8 @@ var ts; reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); } function reportDiagnostics(diagnostics, host) { - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; reportDiagnostic(diagnostic, host); } } @@ -55949,73 +56773,8 @@ var ts; function reportDiagnosticSimply(diagnostic, host) { ts.sys.write(ts.formatDiagnostics([diagnostic], host)); } - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; - var gutterSeparator = " "; - var resetEscapeSequence = "\u001b[0m"; - var ellipsis = "..."; - function getCategoryFormat(category) { - switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; - } - } - function formatAndReset(text, formatStyle) { - return formatStyle + text + resetEscapeSequence; - } function reportDiagnosticWithColorAndContext(diagnostic, host) { - var output = ""; - if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; - var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; - var gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - output += ts.sys.newLine; - for (var i = firstLine; i <= lastLine; i++) { - if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; - i = lastLine - 1; - } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); - lineContent = lineContent.replace("\t", " "); - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; - if (i === firstLine) { - var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - output += lineContent.replace(/./g, "~"); - } - output += resetEscapeSequence; - output += ts.sys.newLine; - } - output += ts.sys.newLine; - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; - } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine + ts.sys.newLine; - ts.sys.write(output); + ts.sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + ts.sys.newLine + ts.sys.newLine); } function reportWatchDiagnostic(diagnostic) { var output = new Date().toLocaleTimeString() + " - "; diff --git a/lib/tsserver.js b/lib/tsserver.js index 05f4c1e5fd1..8c7f8cc868d 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -332,9 +332,10 @@ var ts; SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -469,6 +470,12 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -478,12 +485,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -604,6 +619,11 @@ var ts; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -671,21 +691,21 @@ var ts; TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; @@ -1011,6 +1031,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1025,14 +1046,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1288,6 +1312,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1492,6 +1525,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -2516,6 +2571,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3571,6 +3630,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -3678,7 +3738,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -3873,6 +3933,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4168,6 +4236,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4213,6 +4282,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4294,6 +4365,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -4322,12 +4396,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -4611,6 +4684,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -4744,12 +4819,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -4779,7 +4860,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -5164,9 +5244,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -5323,26 +5401,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5549,10 +5629,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -5804,6 +5880,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -6028,6 +6113,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -6434,9 +6523,6 @@ var ts; } ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } var func = param.parent; var tags = getJSDocTags(func, 286); if (!param.name) { @@ -6455,6 +6541,18 @@ var ts; } } ts.getJSDocParameterTags = getJSDocParameterTags; + function getParameterFromJSDoc(node) { + var name = node.parameterName.text; + var grandParent = node.parent.parent; + ts.Debug.assert(node.parent.kind === 283); + if (!isFunctionLike(grandParent)) { + return undefined; + } + return ts.find(grandParent.parameters, function (p) { + return p.name.kind === 71 && p.name.text === name; + }); + } + ts.getParameterFromJSDoc = getParameterFromJSDoc; function getJSDocType(node) { var tag = getFirstJSDocTag(node, 288); if (!tag && node.kind === 146) { @@ -6581,19 +6679,14 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { @@ -6695,21 +6788,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -6737,12 +6828,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6787,7 +6879,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -7062,6 +7155,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -7165,12 +7260,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -7259,7 +7355,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -7311,7 +7407,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -7800,13 +7896,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -8054,10 +8150,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -8125,9 +8217,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -8325,6 +8428,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8411,6 +8515,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -8433,6 +8541,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -8504,8 +8616,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8621,6 +8733,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -8880,6 +9034,27 @@ var ts; return identifier.length >= 3 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 && identifier.charCodeAt(2) === 95 ? identifier.substr(1) : identifier; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; })(ts || (ts = {})); var ts; (function (ts) { @@ -9424,9 +9599,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -10536,15 +10712,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -10632,237 +10817,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -10873,42 +10833,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -10945,6 +10869,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -10966,7 +10910,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -10979,7 +10940,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -10989,7 +10950,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11057,6 +11018,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -11102,9 +11306,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11117,9 +11320,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11167,9 +11369,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11359,10 +11561,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11489,6 +11691,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -11503,6 +11718,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -11512,7 +11731,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11532,35 +11751,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -11779,6 +11969,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -11827,6 +12050,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -11847,7 +12112,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -11888,6 +12153,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -11918,7 +12195,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12104,19 +12382,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -12131,6 +12396,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -12156,20 +12433,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12178,10 +12441,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12191,12 +12454,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12205,10 +12480,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -12220,10 +12495,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12234,10 +12509,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12247,10 +12522,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -12345,14 +12619,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -12373,6 +12647,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -12683,6 +12980,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -12923,7 +13239,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13030,9 +13348,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -13143,16 +13462,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -13321,6 +13630,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -13473,7 +13810,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -14130,6 +14467,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -18472,6 +18811,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -19232,7 +19573,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -19260,7 +19601,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -19293,19 +19634,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -19323,15 +19665,8 @@ var ts; case 243: return node.isExportEquals ? "export=" : "default"; case 194: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2: - return "export="; - case 1: - case 4: - case 5: - return node.left.name.text; - case 3: - return node.left.expression.name.text; + if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; @@ -19401,9 +19736,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -19423,6 +19758,8 @@ var ts; } } else { + if (node.kind === 290) + ts.Debug.assert(ts.isInJavaScriptFile(node)); var isJSDocTypedefInJSDocNamespace = node.kind === 290 && node.name && node.name.kind === 71 && @@ -19552,9 +19889,7 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } + ts.forEach(node.jsDoc, bind); if (checkUnreachable(node)) { bindEachChild(node); return; @@ -20604,9 +20939,7 @@ var ts; } node.parent = parent; var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } + bindJSDocTypedefTagIfAny(node); bindWorker(node); if (node.kind > 142) { var saveParent = parent; @@ -20666,7 +20999,7 @@ var ts; function bindWorker(node) { switch (node.kind) { case 71: - if (node.isInJSDocNamespace) { + if (ts.isInJavaScriptFile(node) && node.isInJSDocNamespace) { var parentNode = node.parent; while (parentNode && parentNode.kind !== 290) { parentNode = parentNode.parent; @@ -20734,10 +21067,7 @@ var ts; return bindVariableDeclarationOrBindingElement(node); case 149: case 148: - case 276: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); - case 291: - return bindJSDocProperty(node); + return bindPropertyWorker(node); case 261: case 262: return bindPropertyOrMethodOrAccessor(node, 4, 0); @@ -20775,13 +21105,10 @@ var ts; return bindPropertyOrMethodOrAccessor(node, 65536, 74687); case 160: case 161: - case 279: return bindFunctionOrConstructorType(node); case 163: case 172: - case 292: - case 275: - return bindAnonymousDeclaration(node, 2048, "__type"); + return bindAnonymousTypeWorker(node); case 178: return bindObjectLiteralExpression(node); case 186: @@ -20798,11 +21125,6 @@ var ts; return bindClassLikeDeclaration(node); case 230: return bindBlockScopedDeclaration(node, 64, 792968); - case 290: - if (!node.fullName || node.fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); - } - break; case 231: return bindBlockScopedDeclaration(node, 524288, 793064); case 232: @@ -20835,8 +21157,37 @@ var ts; } case 234: return updateStrictModeStatementList(node.statements); + default: + if (ts.isInJavaScriptFile(node)) + return bindJSDocWorker(node); } } + function bindJSDocWorker(node) { + switch (node.kind) { + case 276: + return bindPropertyWorker(node); + case 291: + return declareSymbolAndAddToSymbolTable(node, 4, 0); + case 279: + return bindFunctionOrConstructorType(node); + case 292: + case 275: + return bindAnonymousTypeWorker(node); + case 290: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048, "__type"); + } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; if (parameterName && parameterName.kind === 71) { @@ -21053,7 +21404,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -21068,7 +21419,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21083,7 +21434,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -21096,10 +21447,8 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { node.flowNode = currentFlow; @@ -21108,9 +21457,6 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4, 0); - } function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); @@ -21831,6 +22177,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -21975,13 +22322,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -22054,11 +22404,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -22315,16 +22667,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -22397,9 +22749,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -22407,7 +22756,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -22435,7 +22784,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -22510,7 +22860,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -22519,7 +22873,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -22566,12 +22920,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -22580,7 +22934,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -22589,7 +22943,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -22611,7 +22965,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -22658,7 +23012,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -22668,7 +23022,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -22765,6 +23129,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -22796,13 +23164,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -22814,7 +23182,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -22917,10 +23285,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -22936,7 +23304,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -23058,7 +23426,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -23078,6 +23446,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -23137,7 +23510,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -23278,7 +23650,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -23548,34 +23920,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -23585,12 +23982,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -23607,23 +24004,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -23643,8 +24042,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -23655,72 +24054,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -23728,12 +24108,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -23775,41 +24155,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -23817,7 +24208,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -23827,48 +24218,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -23877,74 +24292,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -23952,18 +24414,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -23972,20 +24434,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -24011,28 +24463,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -24050,12 +24503,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -24091,13 +24546,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -24140,7 +24596,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -24205,12 +24661,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -24547,7 +25006,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -24798,10 +25257,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -24922,7 +25378,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -25022,7 +25478,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -25100,6 +25556,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -25116,16 +25573,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -25335,7 +25799,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -25391,7 +25855,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -25567,11 +26031,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -25735,77 +26200,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -26037,7 +26505,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -26114,8 +26582,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -26259,7 +26727,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -26379,6 +26847,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -26435,8 +26924,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -26478,7 +26967,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -26492,12 +26981,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -26563,7 +27052,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -26926,8 +27415,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -27054,8 +27544,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -27085,7 +27575,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -27097,7 +27587,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -27117,7 +27607,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -27129,7 +27619,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -27166,14 +27655,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -27232,16 +27722,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -27463,14 +27953,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -27478,8 +27968,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -27600,8 +28090,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -27652,9 +28142,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -27684,12 +28174,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -27704,11 +28194,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -27733,7 +28223,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -27865,7 +28355,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -27882,11 +28372,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -27913,15 +28403,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -27932,11 +28423,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -28191,7 +28684,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -28602,29 +29095,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -28635,42 +29126,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -28854,24 +29350,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -29220,10 +29698,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -29320,23 +29798,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -29447,7 +29936,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -29470,11 +29959,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -29513,8 +30002,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -29592,8 +30081,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -29601,8 +30090,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -29625,7 +30114,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -29665,27 +30154,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -29693,43 +30182,43 @@ 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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -29874,7 +30363,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -29951,7 +30440,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -29984,20 +30473,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -30010,7 +30489,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -30098,26 +30577,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -30200,8 +30678,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -30276,7 +30754,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -30286,7 +30764,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -30351,7 +30829,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -30411,8 +30889,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -30428,15 +30906,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -30638,7 +31117,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -30661,8 +31140,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30731,8 +31210,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -30758,7 +31237,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -30784,7 +31263,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -30904,7 +31383,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -31337,6 +31816,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -31391,7 +31886,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -31421,12 +31916,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -32121,8 +32616,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -32213,7 +32708,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -32228,7 +32723,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -32366,6 +32861,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -32425,6 +32922,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -32442,6 +32943,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -32451,37 +32955,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -32491,9 +32995,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -32503,11 +33006,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -32562,7 +33069,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -32596,6 +33114,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -32605,6 +33137,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -32630,6 +33163,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -32675,7 +33209,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -32833,6 +33367,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -32844,7 +33396,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -32862,36 +33423,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -32966,42 +33509,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -33037,7 +33544,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -33053,6 +33560,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -33160,7 +33768,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -33183,8 +33797,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -33271,7 +33885,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -33507,7 +34121,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -33585,7 +34199,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -33613,7 +34227,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -33654,25 +34268,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -33682,14 +34327,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -33820,7 +34457,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -33947,8 +34584,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -34092,7 +34729,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -34156,10 +34793,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -34443,15 +35080,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -34531,7 +35168,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -34574,8 +35211,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -34589,8 +35226,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -34599,8 +35236,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -34635,7 +35272,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -34907,7 +35544,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -34961,7 +35598,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -35043,12 +35680,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -35088,9 +35725,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -35144,7 +35781,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -35441,17 +36078,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -35474,7 +36108,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -35595,7 +36229,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -35669,7 +36303,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -35807,7 +36442,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -35846,7 +36481,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -35896,16 +36531,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -35916,7 +36551,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -36024,7 +36659,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -36037,8 +36672,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -36087,11 +36722,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -36287,7 +36923,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -36297,6 +36935,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -36323,7 +36998,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -36332,15 +37007,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -36453,15 +37128,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -36539,7 +37215,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -36601,7 +37277,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -36615,7 +37291,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -36811,7 +37487,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -36917,11 +37593,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -37371,11 +38048,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -37590,7 +38270,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -37609,7 +38289,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -37624,13 +38304,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -37649,7 +38326,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -37732,88 +38409,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -37826,75 +38496,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -37917,7 +38565,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -38142,6 +38790,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -38744,6 +39395,10 @@ var ts; return entityNameSymbol; } } + if (entityName.parent.kind === 286) { + var parameter = ts.getParameterFromJSDoc(entityName.parent); + return parameter && parameter.symbol; + } if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; @@ -38788,7 +39443,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -38901,7 +39556,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -38963,16 +39618,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -39233,7 +39888,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -39261,7 +39916,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -39273,15 +39928,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -39360,7 +40006,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -39507,7 +40152,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -39534,9 +40179,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -40565,6 +41211,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -40675,49 +41332,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -40728,20 +41395,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -40778,12 +41431,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -40800,6 +41453,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -40844,6 +41499,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -40852,6 +41511,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -40876,8 +41537,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -40886,6 +41545,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -40910,6 +41571,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -40965,6 +41628,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -41303,6 +41973,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -41753,7 +42426,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -42542,15 +43215,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -42837,7 +43505,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -42884,9 +43557,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -43019,7 +43692,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -43329,7 +44002,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -43574,7 +44247,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -43642,19 +44315,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -43781,6 +44449,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -43788,19 +44459,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -43809,12 +44478,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -44046,12 +44710,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -44063,11 +44737,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -44086,7 +44760,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -44524,7 +45198,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -44666,7 +45340,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -45529,12 +46203,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -46422,7 +47097,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -46590,8 +47265,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -48277,7 +48951,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -48440,9 +49114,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -48946,9 +49620,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -49461,9 +50133,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -49754,7 +50426,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -49869,7 +50541,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -49927,7 +50599,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -50097,7 +50769,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -50122,11 +50794,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -50530,8 +51202,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -50544,23 +51215,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -50570,12 +51248,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -50645,7 +51317,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50873,7 +51545,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -50970,7 +51642,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50982,12 +51654,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -51001,7 +51667,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -51016,6 +51682,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -51023,15 +51702,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -51052,7 +51738,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -51104,7 +51790,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -51112,7 +51799,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -51307,6 +51994,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -51565,7 +52257,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -52328,7 +53020,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -52359,7 +53051,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -52445,7 +53137,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -52521,7 +53215,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -52721,7 +53415,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -52741,7 +53435,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -52803,6 +53497,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -52828,6 +53524,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -52850,6 +53547,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -52964,7 +53662,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -53002,9 +53702,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -53015,8 +53721,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -53029,7 +53740,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -53105,7 +53816,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -53196,7 +53907,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -53875,6 +54586,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -54123,6 +54837,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -54300,7 +55023,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -54514,14 +55239,17 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -54735,6 +55463,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -54784,6 +55589,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -54826,7 +55632,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -54875,7 +55682,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -54908,45 +55716,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -54955,15 +55782,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -54982,67 +55806,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -55050,11 +55880,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -55066,8 +55901,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -55407,7 +56241,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -55438,7 +56272,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -55479,13 +56312,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -55508,45 +56341,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -55682,10 +56520,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -55734,7 +56572,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -55831,12 +56669,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -56919,49 +57757,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -56971,37 +57788,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -57032,9 +57819,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -57051,9 +57835,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -57509,7 +58350,6 @@ var ts; case 148: case 261: case 262: - case 264: case 151: case 150: case 152: @@ -57526,9 +58366,11 @@ var ts; case 231: case 163: return 2; + case 264: case 229: - case 232: return 1 | 2; + case 232: + return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -57545,7 +58387,7 @@ var ts; case 238: case 243: case 244: - return 1 | 2 | 4; + return 7; case 265: return 4 | 1; } @@ -57700,7 +58542,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -57715,31 +58557,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -58019,69 +58836,45 @@ var ts; } ts.findContainingList = findContainingList; function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTouchingToken(sourceFile, position, includeJsDocComment, includeItemAtEndPosition) { return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -58089,7 +58882,7 @@ var ts; } } function findTokenOnLeftOfPosition(file, position) { - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -58175,12 +58968,8 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); if (!token) { return false; } @@ -58203,26 +58992,35 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end); }); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, false); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { + return kind === 2 || + !(text.charCodeAt(end - 1) === 47 && text.charCodeAt(end - 2) === 42); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); function jsDocPrefix(c) { @@ -58232,7 +59030,7 @@ var ts; } ts.hasDocComment = hasDocComment; function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); + var node = ts.getTokenAtPosition(sourceFile, position, false); if (ts.isToken(node)) { switch (node.kind) { case 104: @@ -58336,6 +59134,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -58376,25 +59177,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119: @@ -58654,8 +59457,8 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; @@ -58677,7 +59480,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -58689,7 +59492,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); @@ -59202,7 +60005,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -59210,8 +60013,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60070,8 +60873,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -60115,7 +60918,7 @@ var ts; return ts.deduplicate(nonRelativeModules); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, false); if (!token) { return undefined; } @@ -60328,7 +61131,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; } @@ -60352,13 +61155,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -60403,8 +61209,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -60461,10 +61267,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -60492,9 +61299,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -60502,16 +61310,20 @@ var ts; if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -60559,10 +61371,10 @@ var ts; var requestJsDocTagName = false; var requestJsDocTag = false; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, false); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -60592,7 +61404,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -60612,7 +61424,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, false); if (contextToken) { if (isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); @@ -60663,6 +61475,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -60693,7 +61506,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; @@ -60735,6 +61548,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -60742,6 +61556,10 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { @@ -60871,12 +61689,14 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174) { @@ -60893,7 +61713,10 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -60904,10 +61727,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -60933,6 +61752,42 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + isMemberCompletion = true; + isNewIdentifierLocation = true; + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32; + break; + } + } + if (!(classElementModifierFlags & 8)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -60961,6 +61816,37 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + case 26: + case 25: + case 18: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61050,7 +61936,7 @@ var ts; containingNodeKind === 231 || isFunction(containingNodeKind); case 115: - return containingNodeKind === 149; + return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: return containingNodeKind === 146 || (contextToken.parent && contextToken.parent.parent && @@ -61063,13 +61949,16 @@ var ts; return containingNodeKind === 242 || containingNodeKind === 246 || containingNodeKind === 240; + case 125: + case 135: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } case 75: case 83: case 109: case 89: case 104: - case 125: - case 135: case 91: case 110: case 76: @@ -61077,6 +61966,10 @@ var ts; case 138: return true; } + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61108,7 +62001,7 @@ var ts; var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -61134,7 +62027,7 @@ var ts; m.kind !== 154) { continue; } - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -61144,17 +62037,51 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + if (m.kind !== 149 && + m.kind !== 151 && + m.kind !== 153 && + m.kind !== 154) { + continue; + } + if (isCurrentlyEditingNode(m)) { + continue; + } + if (ts.hasModifier(m, 8)) { + continue; + } + var mIsStatic = ts.hasModifier(m, 32); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { @@ -61163,6 +62090,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(typeChecker, symbol, location); @@ -61198,6 +62128,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114: + case 113: + case 112: + case 117: + case 115: + case 123: + case 131: + case 125: + case 135: + case 120: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -61213,9 +62164,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingWord(sourceFile, position, true); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -61227,8 +62178,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -61954,6 +62905,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62019,10 +62973,41 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -62044,7 +63029,7 @@ var ts; }); } function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -62072,25 +63057,20 @@ var ts; } } }); - if (sourceFile.flags & 65536) { - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 || decl.kind === 244) { - return decl; + switch (decl.kind) { + case 181: + case 238: + case 244: + return decl; + case 248: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248); - return decl.parent; } function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); @@ -62209,12 +63189,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); - ts.Debug.assert(!!name); - return name; } function skipExportSpecifierSymbol(symbol, checker) { if (symbol.declarations) @@ -62257,12 +63238,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; if (definition) { @@ -62272,39 +63254,44 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position, false); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265) { + return undefined; + } + var checker = program.getTypeChecker(); if (node.parent.kind === 262) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -62314,10 +63301,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -62454,7 +63437,7 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265) { return undefined; @@ -62465,6 +63448,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { if (!options.implementations && node.kind === 9) { @@ -62472,12 +63456,59 @@ var ts; } return undefined; } - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9) { + return false; + } + switch (node.parent.kind) { + case 233: + case 248: + case 238: + case 244: + return true; + case 181: + return ts.isRequireCall(node.parent, false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265: + break; + case 233: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); @@ -62672,7 +63703,11 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; if (!symbolName || !symbolName.length) { return positions; @@ -62697,15 +63732,11 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + var node = ts.getTouchingWord(sourceFile, position, false); + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -62714,30 +63745,30 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, true); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -62751,15 +63782,13 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments || container.jsDoc !== undefined); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (!isValidReferencePosition(referenceLocation, search.text)) { if (!state.implementations && (state.findInStrings && ts.isInString(sourceFile, position) || state.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); @@ -62862,7 +63891,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63092,10 +64121,10 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; - var node = ts.getTouchingWord(sourceFile, position); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || node.kind !== 97) { continue; } @@ -63138,13 +64167,13 @@ var ts; if (searchSpaceNode.kind === 265) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -63153,7 +64182,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || !ts.isThis(node)) { return; } @@ -63188,10 +64217,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -63199,9 +64228,9 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; + var node_7 = ts.getTouchingWord(sourceFile, position, false); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); } @@ -63329,20 +64358,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -63463,7 +64492,7 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -63481,12 +64510,10 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 71 && - (node.parent === declaration || - (declaration.kind === 242 && declaration.parent && declaration.parent.kind === 241))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } if (node.parent.kind === 262) { @@ -63500,27 +64527,17 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -63533,13 +64550,13 @@ var ts; return undefined; } if (type.flags & 65536 && !(type.flags & 16)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -63547,6 +64564,23 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239: + case 237: + return true; + case 242: + return declaration.parent.kind === 241; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -63611,7 +64645,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -63638,7 +64672,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -63707,6 +64741,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -63717,8 +64752,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -63805,7 +64838,7 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -64092,8 +65125,8 @@ var ts; } }); }; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } rawItems = ts.filter(rawItems, function (item) { @@ -64134,16 +65167,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64167,8 +65203,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64201,6 +65238,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64209,8 +65247,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64424,8 +65462,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64503,9 +65541,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64522,7 +65560,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -65742,7 +66780,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 181 || node.parent.kind === 182) { + if (ts.isCallOrNewExpression(node.parent)) { var callExpression = node.parent; if (node.kind === 27 || node.kind === 19) { @@ -66120,7 +67158,7 @@ var ts; } } var callExpressionLike = void 0; - if (location.kind === 181 || location.kind === 182) { + if (ts.isCallOrNewExpression(location)) { callExpressionLike = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -66185,24 +67223,29 @@ var ts; } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { + return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 152) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; } } } @@ -66266,9 +67309,9 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 145); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; + var decl = ts.getDeclarationOfKind(symbol, 145); + ts.Debug.assert(decl !== undefined); + var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); @@ -66302,7 +67345,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } } } @@ -66548,7 +67591,7 @@ var ts; ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); ts.addRange(diagnostics, program.getOptionsDiagnostics()); } - program.emit(); + program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } @@ -66822,9 +67865,10 @@ var ts; var formatting; (function (formatting) { var FormattingContext = (function () { - function FormattingContext(sourceFile, formattingRequestKind) { + function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; + this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); @@ -67062,7 +68106,7 @@ var ts; this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); @@ -67070,10 +68114,10 @@ var ts; this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -67090,11 +68134,12 @@ var ts; this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); @@ -67102,8 +68147,8 @@ var ts; this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); @@ -67134,6 +68179,41 @@ var ts; this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -67177,7 +68257,25 @@ var ts; this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator + this.NoSpaceBeforeNonNullAssertionOperator, + this.NoSpaceAfterNewKeywordOnConstructorSignature + ]; + this.UserConfigurableRules = [ + this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, + this.SpaceAfterComma, this.NoSpaceAfterComma, + this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, + this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, + this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, + this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, + this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, + this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, + this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, + this.NewLineBeforeOpenBraceInControl, + this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, + this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion ]; this.LowPriorityCommonRules = [ this.NoSpaceBeforeSemicolon, @@ -67188,41 +68286,6 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; @@ -67233,6 +68296,18 @@ var ts; } throw new Error("Unknown rule"); }; + Rules.IsOptionEnabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + }; + Rules.IsOptionDisabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + }; + Rules.IsOptionDisabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + }; + Rules.IsOptionEnabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + }; Rules.IsForContext = function (context) { return context.contextNode.kind === 214; }; @@ -67448,6 +68523,9 @@ var ts; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 163; }; + Rules.IsConstructorSignatureContext = function (context) { + return context.contextNode.kind === 156; + }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 27 && token.kind !== 29) { return false; @@ -67529,8 +68607,7 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); @@ -67638,27 +68715,14 @@ var ts; (function (formatting) { var Shared; (function (Shared) { - var TokenRangeAccess = (function () { - function TokenRangeAccess(from, to, except) { - this.tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } - TokenRangeAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenRangeAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0; token <= 142; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -67666,9 +68730,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -67679,18 +68743,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0; token <= 142; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -67698,51 +68758,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92, 93, 142, 118, 126]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43, 44, 52, 51]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 71, 19, 21, 17, 99, 94]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([71, 133, 136, 122, 137, 105, 119]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); + TokenRange.Keywords = TokenRange.FromRange(72, 142); + TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92, 93, 142, 118, 126 + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43, 44, 52, 51 + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8, 71, 19, 21, + 17, 99, 94 + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71, 133, 136, 122, + 137, 105, 119 + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -67753,6 +68842,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -67768,121 +68859,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -68067,7 +69046,7 @@ var ts; return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -68150,7 +69129,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -68923,9 +69902,7 @@ var ts; if (node.kind === 20) { return -1; } - if (node.parent && (node.parent.kind === 181 || - node.parent.kind === 182) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -69205,7 +70182,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, false); if (nextToken && isSeparator(node, nextToken)) { var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); var nextElement = containingList[index + 1]; @@ -69214,7 +70191,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -69282,7 +70259,7 @@ var ts; } var end = after.getEnd(); if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, false); if (nextToken && isSeparator(after, nextToken)) { var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); @@ -69421,7 +70398,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3, node, sourceFile, writer); @@ -69450,27 +70427,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); var newNode = ts.nodeIsSynthesized(visited) ? visited : (Proxy.prototype = visited, new Proxy()); @@ -69513,6 +70471,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -69579,14 +70547,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -69609,6 +70577,48 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69619,7 +70629,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -69672,13 +70682,14 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); if (token.kind !== 71) { return undefined; } @@ -69750,7 +70761,7 @@ var ts; if (!isStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignatureDeclaration(undefined, undefined, [indexingParameter], typeNode); + var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ @@ -69764,6 +70775,56 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4) { + flags |= 1920; + } + if (meaning & 2) { + flags |= 793064; + } + if (meaning & 1) { + flags |= 107455; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69778,7 +70839,7 @@ var ts; function getActionForClassLikeMissingAbstractMember(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -69813,7 +70874,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 99) { return undefined; } @@ -69858,7 +70919,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 123) { return undefined; } @@ -69882,7 +70943,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 && ts.isClassLike(classDeclNode))) { return undefined; @@ -69920,7 +70981,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 71) { return undefined; } @@ -69946,126 +71007,131 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); if (token.kind === 21) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, false); } switch (token.kind) { case 71: - switch (token.parent.kind) { - case 226: - switch (token.parent.parent.parent.kind) { - case 214: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215: - return undefined; - case 260: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - case 145: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); - case 242: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); - } - else { - return deleteNodeInList(token.parent); - } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); - } - else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149: case 240: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226: + return deleteVariableDeclaration(token.parent); + case 145: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); + if (!previousToken || previousToken.kind !== 27) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + case 237: + var importEquals = ts.getAncestor(token, 237); + return deleteNode(importEquals); + case 242: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = ts.getAncestor(token, 238); + return deleteNode(importSpec); + } + else { + return deleteNodeInList(token.parent); + } + case 239: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238); + return deleteNode(importDecl); + } + else { + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); + if (nextToken && nextToken.kind === 26) { + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, false); + if (previousToken && previousToken.kind === 26) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215: + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -70096,6 +71162,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -70178,342 +71253,335 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, false, true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, false, true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238) { + return node; } - } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240) { + namespaceImportDeclaration = declaration; } - if (node.kind === 237) { - return node; + else { + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 || statement.kind === 238) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), undefined) + : isNamespaceImport + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -70535,7 +71603,7 @@ var ts; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -70628,7 +71696,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -70677,7 +71745,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -70718,7 +71786,7 @@ var ts; return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { @@ -70736,8 +71804,173 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + if (!(symbol.flags & 4)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + case 187: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + if (arrowFunctionBody.kind === 207) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + default: + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186) { + return undefined; + } + if (node.name.kind !== 71) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : @@ -70788,6 +72021,7 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + ts.Debug.assert(token !== 1); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -70815,27 +72049,31 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143) { + if (ts.isJSDocTag(this)) { + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + } + else if (this.kind >= 143) { + var children_4 = []; ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; var pos_3 = this.pos; var useJSDocScanner_1 = this.kind >= 283 && this.kind <= 293; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, node.pos, useJSDocScanner_1); } - children.push(node); + children_4.push(node); if (!isJSDocTagNode) { pos_3 = node.end; } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, nodes.pos, useJSDocScanner_1); } - children.push(_this.createSyntaxList(nodes)); + children_4.push(_this.createSyntaxList(nodes)); pos_3 = nodes.end; }; if (this.jsDoc) { @@ -70847,11 +72085,14 @@ var ts; pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); + this.addSyntheticNodes(children_4, pos_3, this.end); } ts.scanner.setText(undefined); + this._children = children_4; + } + else { + this._children = ts.emptyArray; } - this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -71116,13 +72357,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -71465,7 +72707,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -71489,9 +72731,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -71667,7 +72906,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -71718,7 +72957,7 @@ var ts; } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -71732,7 +72971,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -71765,11 +73004,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); @@ -71807,7 +73046,7 @@ var ts; } function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, false); if (node === sourceFile) { return; } @@ -71887,7 +73126,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); if (matchKind) { @@ -72017,8 +73256,7 @@ var ts; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -72066,11 +73304,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -72184,20 +73446,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -72734,6 +73996,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -74423,7 +75688,7 @@ var ts; var oldProgram = this.program; this.program = this.languageService.getProgram(); var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { hasChanges = true; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -74680,6 +75945,11 @@ var ts; return; } var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.allowLocalPluginLoads) { + var local = ts.getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); + searchPaths.unshift(local); + } if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -75064,6 +76334,7 @@ var ts; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); @@ -76263,6 +77534,9 @@ var ts; CommandNames.GetCodeFixes = "getCodeFixes"; CommandNames.GetCodeFixesFull = "getCodeFixes-full"; CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; + CommandNames.GetApplicableRefactors = "getApplicableRefactors"; + CommandNames.GetRefactorCodeActions = "getRefactorCodeActions"; + CommandNames.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); @@ -76596,6 +77870,15 @@ var ts; _a[CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, + _a[CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[CommandNames.GetRefactorCodeActions] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, true)); + }, + _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -76626,7 +77909,8 @@ var ts; throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); @@ -77562,6 +78846,47 @@ var ts; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + var position = undefined; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return { position: position, textRange: textRange }; + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + }; + Session.prototype.getRefactorCodeActions = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + var result = project.getLanguageService().getRefactorCodeActions(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactorName); + if (simplifiedResult) { + return { + actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + }; + } + else { + return { + actions: result + }; + } + }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; if (args.errorCodes.length === 0) { @@ -77569,8 +78894,7 @@ var ts; } var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = getStartPosition(); - var endPosition = getEndPosition(); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); if (!codeActions) { @@ -77582,12 +78906,24 @@ var ts; else { return codeActions; } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition = undefined, endPosition = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; }; Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { var _this = this; @@ -78878,7 +80214,8 @@ var ts; logger: logger, canUseEvents: canUseEvents, globalPlugins: options.globalPlugins, - pluginProbeLocations: options.pluginProbeLocations + pluginProbeLocations: options.pluginProbeLocations, + allowLocalPluginLoads: options.allowLocalPluginLoads }) || this; if (telemetryEnabled && typingsInstaller) { typingsInstaller.setTelemetrySender(_this); @@ -79121,12 +80458,11 @@ var ts; sys.gc = function () { return global.gc(); }; } sys.require = function (initialDir, moduleName) { - var result = ts.nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, undefined, true); try { - return { module: require(result.resolvedModule.resolvedFileName), error: undefined }; + return { module: require(ts.resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; } - catch (e) { - return { module: undefined, error: e }; + catch (error) { + return { module: undefined, error: error }; } }; var cancellationToken; @@ -79152,6 +80488,7 @@ var ts; var typingSafeListLocation = server.findArgument("--typingSafeListLocation"); var globalPlugins = (server.findArgument("--globalPlugins") || "").split(","); var pluginProbeLocations = (server.findArgument("--pluginProbeLocations") || "").split(","); + var allowLocalPluginLoads = server.hasArgument("--allowLocalPluginLoads"); var useSingleInferredProject = server.hasArgument("--useSingleInferredProject"); var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition"); var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); @@ -79167,7 +80504,8 @@ var ts; telemetryEnabled: telemetryEnabled, logger: logger, globalPlugins: globalPlugins, - pluginProbeLocations: pluginProbeLocations + pluginProbeLocations: pluginProbeLocations, + allowLocalPluginLoads: allowLocalPluginLoads }; var ioSession = new IOSession(options); process.on("uncaughtException", function (err) { diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 189883c63e6..566cb7d6cdf 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -352,9 +352,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -482,9 +483,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -495,7 +498,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -503,7 +506,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -516,7 +519,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -528,7 +531,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -537,7 +540,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -559,7 +562,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -581,7 +584,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -589,7 +592,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -926,7 +929,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -991,7 +994,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1051,6 +1054,10 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1172,7 +1179,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1185,11 +1192,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1213,7 +1220,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1266,13 +1273,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1298,13 +1305,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1435,7 +1442,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1626,11 +1633,11 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1640,37 +1647,47 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1831,18 +1848,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1854,15 +1871,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } const enum ObjectFlags { Class = 1, @@ -1896,7 +1915,7 @@ declare namespace ts { } interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -1932,7 +1951,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } const enum IndexKind { @@ -1961,9 +1980,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2204,6 +2223,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2362,13 +2382,13 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2384,7 +2404,7 @@ declare namespace ts { error?: Diagnostic; }; function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -2395,9 +2415,6 @@ declare namespace ts { }; } declare namespace ts { - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -2456,6 +2473,7 @@ declare namespace ts { function getParseTreeNode(node: Node): Node; function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; function unescapeIdentifier(identifier: string): string; + function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; } declare namespace ts { function createNodeArray(elements?: T[], hasTrailingComma?: boolean): NodeArray; @@ -2466,6 +2484,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; function createLoopVariable(): Identifier; function createUniqueName(text: string): Identifier; @@ -2480,58 +2499,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2539,6 +2519,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2580,7 +2599,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2600,16 +2619,15 @@ 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 createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2641,10 +2659,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2653,6 +2680,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2683,20 +2712,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2712,6 +2741,8 @@ declare namespace ts { function createNotEmittedStatement(original: Node): NotEmittedStatement; function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -2745,8 +2776,8 @@ declare namespace ts { function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; function addEmitHelper(node: T, helper: EmitHelper): T; function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; function removeEmitHelper(node: Node, helper: EmitHelper): boolean; @@ -2756,7 +2787,7 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; @@ -2789,6 +2820,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -2931,6 +2963,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -2981,6 +3015,10 @@ declare namespace ts { description: string; changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; caretOffset: number; @@ -3367,6 +3405,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; @@ -3610,6 +3649,9 @@ declare namespace ts.server.protocol { type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; type GetCodeFixes = "getCodeFixes"; type GetSupportedCodeFixes = "getSupportedCodeFixes"; + type GetApplicableRefactors = "getApplicableRefactors"; + type GetRefactorCodeActions = "getRefactorCodeActions"; + type GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; } interface Message { seq: number; @@ -3704,15 +3746,44 @@ declare namespace ts.server.protocol { line: number; offset: number; } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + interface ApplicableRefactorInfo { + name: string; + description: string; + } + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + interface GetRefactorCodeActionsRequest extends Request { + command: CommandTypes.GetRefactorCodeActions; + arguments: GetRefactorCodeActionsRequestArgs; + } + type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & { + refactorName: string; + }; + type RefactorCodeActions = { + actions: protocol.CodeAction[]; + renameLocation?: number; + }; + interface GetRefactorCodeActionsResponse extends Response { + body: RefactorCodeActions; + } interface CodeFixRequest extends Request { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } - interface CodeFixRequestArgs extends FileRequestArgs { + interface FileRangeRequestArgs extends FileRequestArgs { startLine: number; startOffset: number; endLine: number; endOffset: number; + } + interface CodeFixRequestArgs extends FileRangeRequestArgs { errorCodes?: number[]; } interface GetCodeFixesResponse extends Response { @@ -4291,6 +4362,7 @@ declare namespace ts.server.protocol { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; @@ -4408,7 +4480,7 @@ declare namespace ts.server { project: Project; } interface EventSender { - event(payload: any, eventName: string): void; + event(payload: T, eventName: string): void; } namespace CommandNames { const Brace: protocol.CommandTypes.Brace; @@ -4455,6 +4527,9 @@ declare namespace ts.server { const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects; const GetCodeFixes: protocol.CommandTypes.GetCodeFixes; const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes; + const GetApplicableRefactors: protocol.CommandTypes.GetApplicableRefactors; + const GetRefactorCodeActions: protocol.CommandTypes.GetRefactorCodeActions; + const GetRefactorCodeActionsFull: protocol.CommandTypes.GetRefactorCodeActionsFull; } function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; interface SessionOptions { @@ -4470,6 +4545,7 @@ declare namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } class Session implements EventSender { private readonly gcTimer; @@ -4491,7 +4567,7 @@ declare namespace ts.server { logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; - event(info: any, eventName: string): void; + event(info: T, eventName: string): void; output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private semanticCheck(file, project); private syntacticCheck(file, project); @@ -4554,7 +4630,12 @@ declare namespace ts.server { private getNavigationTree(args, simplifiedResult); private getNavigateToItems(args, simplifiedResult); private getSupportedCodeFixes(); + private isLocation(locationOrSpan); + private extractPositionAndRange(args, scriptInfo); + private getApplicableRefactors(args); + private getRefactorCodeActions(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); + private getStartAndEndPosition(args, scriptInfo); private mapCodeAction(codeAction, scriptInfo); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); @@ -5047,6 +5128,7 @@ declare namespace ts.server { throttleWaitMilliseconds?: number; globalPlugins?: string[]; pluginProbeLocations?: string[]; + allowLocalPluginLoads?: boolean; } class ProjectService { readonly typingsCache: TypingsCache; @@ -5076,6 +5158,7 @@ declare namespace ts.server { private readonly eventHandler?; readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; + readonly allowLocalPluginLoads: boolean; constructor(opts: ProjectServiceOptions); ensureInferredProjectsUpToDate_TestOnly(): void; getCompilerOptionsForInferredProjects(): CompilerOptions; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 52c8a2207c4..29316ac6424 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -332,9 +332,10 @@ var ts; SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -469,6 +470,12 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -478,12 +485,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -604,6 +619,11 @@ var ts; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -671,21 +691,21 @@ var ts; TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; @@ -1011,6 +1031,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1025,14 +1046,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1288,6 +1312,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1492,6 +1525,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -2516,6 +2571,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3571,6 +3630,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -3678,7 +3738,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -3873,6 +3933,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4168,6 +4236,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4213,6 +4282,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4294,6 +4365,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -4842,9 +4916,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6855,49 +6930,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -6907,37 +6961,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -6968,9 +6992,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -6987,9 +7008,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -7245,12 +7323,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -7534,6 +7611,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -7667,12 +7746,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -7702,7 +7787,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -8087,9 +8171,7 @@ var ts; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -8246,26 +8328,28 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -8472,10 +8556,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 && isConst(node); } @@ -8727,6 +8807,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151: @@ -8951,6 +9040,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183) { return node.tag; @@ -9357,9 +9450,6 @@ var ts; } ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } var func = param.parent; var tags = getJSDocTags(func, 286); if (!param.name) { @@ -9378,6 +9468,18 @@ var ts; } } ts.getJSDocParameterTags = getJSDocParameterTags; + function getParameterFromJSDoc(node) { + var name = node.parameterName.text; + var grandParent = node.parent.parent; + ts.Debug.assert(node.parent.kind === 283); + if (!isFunctionLike(grandParent)) { + return undefined; + } + return ts.find(grandParent.parameters, function (p) { + return p.name.kind === 71 && p.name.text === name; + }); + } + ts.getParameterFromJSDoc = getParameterFromJSDoc; function getJSDocType(node) { var tag = getFirstJSDocTag(node, 288); if (!tag && node.kind === 146) { @@ -9504,19 +9606,14 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 71 && name.kind !== 9 && name.kind !== 8) { - return false; + switch (name.kind) { + case 71: + case 9: + case 8: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 || parent.kind === 246) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { @@ -9618,21 +9715,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -9660,12 +9755,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -9710,7 +9806,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -9985,6 +10082,8 @@ var ts; return 2; case 198: return 1; + case 297: + return 0; default: return -1; } @@ -10088,12 +10187,13 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -10182,7 +10282,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -10234,7 +10334,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -10723,13 +10823,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; } - else if (options.newLine === 1) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -10977,10 +11077,6 @@ var ts; return node.kind === 71; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { return isIdentifier(node) && node.autoGenerateKind > 0; } @@ -11048,9 +11144,20 @@ var ts; || kind === 153 || kind === 154 || kind === 157 - || kind === 206; + || kind === 206 + || kind === 247; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 + || kind === 155 + || kind === 148 + || kind === 150 + || kind === 157 + || kind === 247; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 @@ -11248,6 +11355,7 @@ var ts; || kind === 198 || kind === 202 || kind === 200 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -11334,6 +11442,10 @@ var ts; return node.kind === 237; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239; } @@ -11356,6 +11468,10 @@ var ts; return node.kind === 246; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 || node.kind === 232; } @@ -11427,8 +11543,8 @@ var ts; || kind === 213 || kind === 220 || kind === 295 - || kind === 298 - || kind === 297; + || kind === 299 + || kind === 298; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -11544,6 +11660,48 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 6) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 ? 8 : + checkFlags & 64 ? 4 : + 16; + var staticModifier = checkFlags & 512 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11803,6 +11961,27 @@ var ts; return identifier.length >= 3 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 && identifier.charCodeAt(2) === 95 ? identifier.substr(1) : identifier; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; })(ts || (ts = {})); var ts; (function (ts) { @@ -11882,15 +12061,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; function createTempVariable(recordTempVariable) { var name = createIdentifier(""); @@ -11978,237 +12166,12 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170); - typeOperatorNode.operator = 127; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -12219,42 +12182,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146); node.decorators = asNodeArray(decorators); @@ -12291,6 +12218,26 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149); node.decorators = asNodeArray(decorators); @@ -12312,7 +12259,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -12325,7 +12289,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -12335,7 +12299,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -12403,6 +12367,249 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170); + node.operator = 127; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174); node.elements = createNodeArray(elements); @@ -12448,9 +12655,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -12463,9 +12669,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -12513,9 +12718,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -12705,10 +12910,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -12835,6 +13040,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205); node.expression = expression; @@ -12849,6 +13067,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206); + } + ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { var block = createSynthesizedNode(207); block.statements = createNodeArray(statements); @@ -12858,7 +13080,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -12878,35 +13100,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209); } @@ -13125,6 +13318,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227); + node.flags |= flags & 3; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228); node.decorators = asNodeArray(decorators); @@ -13173,6 +13399,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); @@ -13193,7 +13461,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233); - node.flags |= flags; + node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -13234,6 +13502,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237); node.decorators = asNodeArray(decorators); @@ -13264,7 +13544,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -13450,19 +13731,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253); node.name = name; @@ -13477,6 +13745,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255); node.expression = expression; @@ -13502,20 +13782,6 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257); node.expression = ts.parenthesizeExpressionForList(expression); @@ -13524,10 +13790,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -13537,12 +13803,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -13551,10 +13829,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { @@ -13566,10 +13844,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -13580,10 +13858,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -13593,10 +13871,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { @@ -13691,14 +13968,14 @@ var ts; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(299); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(298); node.emitNode = {}; node.original = original; return node; @@ -13719,6 +13996,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266); node.sourceFiles = sourceFiles; @@ -14029,6 +14329,25 @@ var ts; } })(ts || (ts = {})); (function (ts) { + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -14269,7 +14588,9 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -14376,9 +14697,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -14489,16 +14811,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { @@ -14667,6 +14979,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166: + case 167: + case 160: + case 161: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { var clone_1 = ts.getMutableClone(originalOuterExpression); @@ -14819,7 +15159,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15476,6 +15816,8 @@ var ts; return visitNode(cbNode, node.expression); case 247: return visitNodes(cbNodes, node.decorators); + case 297: + return visitNodes(cbNodes, node.elements); case 249: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -19818,6 +20160,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -20578,7 +20922,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -20606,7 +20950,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } else { @@ -20639,19 +20983,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -20669,15 +21014,8 @@ var ts; case 243: return node.isExportEquals ? "export=" : "default"; case 194: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2: - return "export="; - case 1: - case 4: - case 5: - return node.left.name.text; - case 3: - return node.left.expression.name.text; + if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; @@ -20747,9 +21085,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -20769,6 +21107,8 @@ var ts; } } else { + if (node.kind === 290) + ts.Debug.assert(ts.isInJavaScriptFile(node)); var isJSDocTypedefInJSDocNamespace = node.kind === 290 && node.name && node.name.kind === 71 && @@ -20898,9 +21238,7 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } + ts.forEach(node.jsDoc, bind); if (checkUnreachable(node)) { bindEachChild(node); return; @@ -21950,9 +22288,7 @@ var ts; } node.parent = parent; var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } + bindJSDocTypedefTagIfAny(node); bindWorker(node); if (node.kind > 142) { var saveParent = parent; @@ -22012,7 +22348,7 @@ var ts; function bindWorker(node) { switch (node.kind) { case 71: - if (node.isInJSDocNamespace) { + if (ts.isInJavaScriptFile(node) && node.isInJSDocNamespace) { var parentNode = node.parent; while (parentNode && parentNode.kind !== 290) { parentNode = parentNode.parent; @@ -22080,10 +22416,7 @@ var ts; return bindVariableDeclarationOrBindingElement(node); case 149: case 148: - case 276: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); - case 291: - return bindJSDocProperty(node); + return bindPropertyWorker(node); case 261: case 262: return bindPropertyOrMethodOrAccessor(node, 4, 0); @@ -22121,13 +22454,10 @@ var ts; return bindPropertyOrMethodOrAccessor(node, 65536, 74687); case 160: case 161: - case 279: return bindFunctionOrConstructorType(node); case 163: case 172: - case 292: - case 275: - return bindAnonymousDeclaration(node, 2048, "__type"); + return bindAnonymousTypeWorker(node); case 178: return bindObjectLiteralExpression(node); case 186: @@ -22144,11 +22474,6 @@ var ts; return bindClassLikeDeclaration(node); case 230: return bindBlockScopedDeclaration(node, 64, 792968); - case 290: - if (!node.fullName || node.fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); - } - break; case 231: return bindBlockScopedDeclaration(node, 524288, 793064); case 232: @@ -22181,8 +22506,37 @@ var ts; } case 234: return updateStrictModeStatementList(node.statements); + default: + if (ts.isInJavaScriptFile(node)) + return bindJSDocWorker(node); } } + function bindJSDocWorker(node) { + switch (node.kind) { + case 276: + return bindPropertyWorker(node); + case 291: + return declareSymbolAndAddToSymbolTable(node, 4, 0); + case 279: + return bindFunctionOrConstructorType(node); + case 292: + case 275: + return bindAnonymousTypeWorker(node); + case 290: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048, "__type"); + } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; if (parameterName && parameterName.kind === 71) { @@ -22399,7 +22753,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -22414,7 +22768,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -22429,7 +22783,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -22442,10 +22796,8 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { node.flowNode = currentFlow; @@ -22454,9 +22806,6 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4, 0); - } function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); @@ -23177,6 +23526,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -23321,13 +23671,16 @@ var ts; tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4, "unknown"); @@ -23400,11 +23753,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -23661,16 +24016,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -23743,9 +24098,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); } @@ -23753,7 +24105,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -23781,7 +24133,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -23856,7 +24209,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; var result; var lastLocation; var propertyWithInvalidInitializer; @@ -23865,7 +24222,7 @@ var ts; var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 793064 && lastLocation.kind !== 283) { @@ -23912,12 +24269,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + if (result = lookup(moduleExports, name, meaning & 8914931)) { break loop; } break; case 232: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; @@ -23926,7 +24283,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455)) { propertyWithInvalidInitializer = location; } } @@ -23935,7 +24292,7 @@ var ts; case 229: case 199: case 230: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -23957,7 +24314,7 @@ var ts; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -24004,7 +24361,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -24014,7 +24371,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -24111,6 +24478,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -24142,13 +24513,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -24160,7 +24531,7 @@ var ts; if (node.kind === 237) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -24263,10 +24634,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); @@ -24282,7 +24653,7 @@ var ts; case 242: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); case 243: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236: @@ -24404,7 +24775,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -24424,6 +24795,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, true); if (ambientModule) { return ambientModule; @@ -24483,7 +24859,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -24624,7 +24999,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && @@ -24894,34 +25269,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -24931,12 +25331,12 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; return undefined; @@ -24953,23 +25353,25 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 16) { - var name = symbolToName(type.symbol, false); + if (type.flags & 256 && !(type.flags & 65536)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064, false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, undefined); + } + if (type.flags & 272) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } if (type.flags & 1024) { return ts.createKeywordTypeNode(105); } @@ -24989,8 +25391,8 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 16384 && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -25001,72 +25403,53 @@ var ts; ts.Debug.assert(!!(type.flags & 32768)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3) { - ts.Debug.assert(!!(type.flags & 32768)); - var name = symbolToName(type.symbol, false); + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & 16384) { - var name = symbolToName(type.symbol, false); - return ts.createTypeReferenceNode(name, undefined); - } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166, unionTypeNodes); + if (type.flags & (65536 | 131072)) { + var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072) { - return ts.createUnionOrIntersectionTypeNode(167, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 | 32)) { ts.Debug.assert(!!(type.flags & 32768)); return createAnonymousTypeNode(type); } if (type.flags & 262144) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -25074,12 +25457,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, false); + var entityName = symbolToName(typeAlias, context, 793064, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -25121,41 +25504,52 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -25163,7 +25557,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -25173,48 +25567,72 @@ var ts; i++; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - var qualifiedNamePart = symbolToName(parent, true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(namePart, undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); } var properties = resolvedType.properties; if (!properties) { @@ -25223,74 +25641,121 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var name = ts.getNameFromIndexInfo(indexInfo); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + } + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064, true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24), ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 | 16777216); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0, true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -25298,18 +25763,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -25318,20 +25783,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -25357,28 +25812,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -25396,12 +25852,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144)) { if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -25437,13 +25895,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -25486,7 +25945,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -25551,12 +26010,15 @@ var ts; else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 && !(type.flags & 65536)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 512) && type.aliasSymbol && @@ -25893,7 +26355,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -26144,10 +26606,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -26268,7 +26727,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -26368,7 +26827,7 @@ var ts; return expr.kind === 177 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? getNullableType(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { @@ -26446,6 +26905,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 ? declaration : @@ -26462,16 +26922,23 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -26681,7 +27148,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; } } } @@ -26737,7 +27204,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -26913,11 +27380,12 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; @@ -27081,77 +27549,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 || + return expr.kind === 9 || expr.kind === 8 || expr.kind === 192 && expr.operator === 38 && expr.operand.kind === 8 || - expr.kind === 71 && !!symbol.exports.get(expr.text); + expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 : 1; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + if (enumType_1.flags & 65536) { + enumType_1.flags |= 256; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -27383,7 +27854,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -27460,8 +27931,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -27605,7 +28076,7 @@ var ts; var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); @@ -27725,6 +28196,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : type.flags & 524288 ? getConstraintOfIndexedAccess(type) : @@ -27781,8 +28273,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -27824,7 +28316,7 @@ var ts; var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 ? globalStringType : - t.flags & 340 ? globalNumberType : + t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 16777216 ? emptyObjectType : @@ -27838,12 +28330,12 @@ var ts; var commonFlags = isUnion ? 0 : 67108864; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -27909,7 +28401,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(getCheckFlags(property) & 16) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -28272,8 +28764,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -28400,8 +28893,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -28431,7 +28924,7 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -28443,7 +28936,7 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -28463,7 +28956,7 @@ var ts; } return instantiation; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -28475,7 +28968,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -28512,14 +29004,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 | 64)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 && node.kind === 277) { return getTypeOfSymbol(symbol); @@ -28578,16 +29071,16 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } links.resolvedSymbol = symbol; links.resolvedType = type; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -28809,14 +29302,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -28824,8 +29317,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -28946,8 +29439,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -28998,9 +29491,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -29030,12 +29523,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & (32 | 64 | 256) ? - indexType.text : + var propName = indexType.flags & 96 ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -29050,11 +29543,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { @@ -29079,7 +29572,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 | 4)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -29211,7 +29704,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -29228,11 +29721,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { + if (rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -29259,15 +29752,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -29278,11 +29772,13 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -29537,7 +30033,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); @@ -29948,29 +30444,27 @@ var ts; type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 65536) !== (target.flags & 65536)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); } enumRelation.set(id, false); return false; @@ -29981,42 +30475,47 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) + var s = source.flags; + var t = target.flags; + if (t & 8192) return false; - if (target.flags & 1 || source.flags & 8192) + if (t & 1 || s & 8192) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 262178 && t & 2) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 84 && t & 4) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 && t & 8) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 256 && t & 256) { + if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 && t & 224 && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) + if (s & 1) return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -30200,24 +30699,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -30566,10 +31047,10 @@ var ts; } } else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (getCheckFlags(sourceProp) & 256) { + if (ts.getCheckFlags(sourceProp) & 256) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -30666,23 +31147,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -30793,7 +31285,7 @@ var ts; } } function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -30816,11 +31308,11 @@ var ts; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isAbstractConstructorType(type) { @@ -30859,8 +31351,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -30938,8 +31430,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -30947,8 +31439,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -30971,7 +31463,7 @@ var ts; return getUnionType(types, true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -31011,27 +31503,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; + return (type.flags & (224 | 2048 | 4096)) !== 0; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { @@ -31039,43 +31531,43 @@ 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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; } function getFalsyFlags(type) { return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.text === "" ? 32 : 0 : - type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 32 ? type.value === "" ? 32 : 0 : + type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : type.flags & 7406; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) - types.push(voidType); - if (flags & 2048) - types.push(undefinedType); - if (flags & 4096) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 ? emptyStringType : + type.flags & 4 ? zeroType : + type.flags & 8 || type === falseType ? falseType : + type.flags & (1024 | 2048 | 4096) || + type.flags & 32 && type.value === "" || + type.flags & 64 && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 | 4096); + return missing === 0 ? type : + missing === 2048 ? getUnionType([type, undefinedType]) : + missing === 4096 ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } @@ -31220,7 +31712,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -31297,7 +31789,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -31330,20 +31822,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -31356,7 +31838,7 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -31444,26 +31926,25 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + var isNonConstructorObject = target.flags & 32768 && + !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -31546,8 +32027,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31622,7 +32103,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -31632,7 +32113,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -31697,7 +32178,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); } @@ -31757,8 +32238,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -31774,15 +32255,16 @@ var ts; return strictNullChecks ? 4079361 : 4194049; } if (flags & 32) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 : 1982209 : - type.text === "" ? 3145473 : 4194049; + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; } if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type.text === "0"; + if (flags & 64) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 : 1982082 : isZero ? 3145346 : 4193922; @@ -31984,7 +32466,7 @@ var ts; } return true; } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -32007,8 +32489,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -32077,8 +32559,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -32104,7 +32586,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -32130,7 +32612,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -32250,7 +32732,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -32683,6 +33165,22 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 || + parent.kind === 181 && parent.expression === node || + parent.kind === 180 && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + } + function getDeclaredOrApparentType(symbol, node) { + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -32737,7 +33235,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -32767,12 +33265,12 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048); + getNullableType(type, 2048); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -33467,8 +33965,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -33559,7 +34057,7 @@ var ts; return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -33574,7 +34072,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -33712,6 +34210,8 @@ var ts; } if (spread.flags & 32768) { spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; spread.symbol = node.symbol; } return spread; @@ -33771,6 +34271,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -33788,6 +34292,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -33797,37 +34304,37 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; if (child.kind === 10) { if (!child.containsOnlyWhiteSpaces) { childrenTypes.push(stringType); @@ -33837,9 +34344,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -33849,11 +34355,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -33908,7 +34418,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -33942,6 +34463,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -33951,6 +34486,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -33976,6 +34512,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -34021,7 +34558,7 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -34179,6 +34716,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -34190,7 +34745,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -34208,36 +34772,18 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; - } - if (getCheckFlags(s) & 6) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216) { - return 4 | 32; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); } function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 || node.kind === 226 ? node.name : node.right; - if (getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -34312,42 +34858,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (getCheckFlags(prop) & 1) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -34383,7 +34893,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -34399,6 +34909,107 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (ts.getCheckFlags(prop) & 1) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -34506,7 +35117,13 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183) { checkExpression(node.template); } @@ -34529,8 +35146,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -34617,7 +35234,7 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -34853,7 +35470,7 @@ var ts; case 71: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { @@ -34931,7 +35548,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183; var isDecorator = node.kind === 147; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -34959,7 +35576,7 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -35000,25 +35617,56 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -35028,14 +35676,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -35166,7 +35806,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -35293,8 +35933,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -35438,7 +36078,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return getNullableType(type, 2048); } } return type; @@ -35502,10 +36142,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -35789,15 +36429,15 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 || - symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + return !!(ts.getCheckFlags(symbol) & 8 || + symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || symbol.flags & 8); @@ -35877,7 +36517,7 @@ var ts; return silentNeverType; } if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37: @@ -35920,8 +36560,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -35935,8 +36575,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -35945,8 +36585,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -35981,7 +36621,7 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { @@ -36253,7 +36893,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { resultType = numberType; } else { @@ -36307,7 +36947,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53: return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54: return getTypeFacts(leftType) & 2097152 ? @@ -36389,12 +37029,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -36434,9 +37074,9 @@ var ts; } switch (node.kind) { case 9: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; case 86: @@ -36490,7 +37130,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 | 262144)); + return maybeTypeOfKind(contextualType, (224 | 262144)); } return false; } @@ -36787,17 +37427,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -36820,7 +37457,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -36941,7 +37578,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -37015,7 +37652,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -37153,7 +37791,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -37192,7 +37830,7 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 340)) { + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1)) { return type; @@ -37242,16 +37880,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -37262,7 +37900,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -37370,7 +38008,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -37383,8 +38021,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -37433,11 +38071,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -37633,7 +38272,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 ? 793064 : 1920) | 8388608, undefined, undefined); if (rootSymbol @@ -37643,6 +38284,43 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167: + case 166: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return undefined; + } + if (commonEntityName) { + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -37669,7 +38347,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -37678,15 +38356,15 @@ var ts; case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -37799,15 +38477,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -37885,7 +38564,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -37947,7 +38626,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -37961,7 +38640,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -38157,7 +38836,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -38263,11 +38942,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -38717,11 +39397,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -38936,7 +39619,7 @@ var ts; } } function getTargetSymbol(s) { - return getCheckFlags(s) & 1 ? s.target : s; + return ts.getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -38955,7 +39638,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { @@ -38970,13 +39653,10 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { continue; } @@ -38995,7 +39675,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -39078,88 +39758,81 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); + nodeLinks.flags |= 16384; var autoValue = 0; - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37: return value_1; case 38: return -value_1; case 52: return ~value_1; } - return undefined; - case 194: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49: return left | right; case 48: return left & right; case 46: return left >> right; @@ -39172,75 +39845,53 @@ var ts; case 38: return left - right; case 42: return left % right; } - return undefined; - case 8: - checkGrammarNumericLiteral(e); - return +e.text; - case 185: - return evalConstant(e.expression); - case 71: - case 180: - case 179: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71) { - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9: + return expr.text; + case 8: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185: + return evaluate(expr.expression); + case 71: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180: + case 179: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = expr.kind === 179 ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - var current = expression; - while (current) { - if (current.kind === 71) { - break; - } - else if (current.kind === 179) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - if (member === propertyDecl) { - return undefined; - } - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 || + node.kind === 179 && isConstantMemberAccess(node.expression) || + node.kind === 180 && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -39263,7 +39914,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -39488,6 +40139,9 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + if (node.kind === 246 && compilerOptions.isolatedModules && !(target.flags & 107455)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -40090,6 +40744,10 @@ var ts; return entityNameSymbol; } } + if (entityName.parent.kind === 286) { + var parameter = ts.getParameterFromJSDoc(entityName.parent); + return parameter && parameter.symbol; + } if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; @@ -40134,7 +40792,7 @@ var ts; if (isInsideWithStatementBody(node)) { return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { @@ -40247,7 +40905,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -40309,16 +40967,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728) { if (symbol.leftSpread) { @@ -40579,7 +41237,7 @@ var ts; else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178)) { @@ -40607,7 +41265,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096) { - type = includeFalsyTypes(type, 2048); + type = getNullableType(type, 2048); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -40619,15 +41277,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -40706,7 +41355,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -40853,7 +41501,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -40880,9 +41528,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -41911,6 +42560,17 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + if (name.parent.propertyName) { + return true; + } + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -42021,49 +42681,59 @@ var ts; if ((kind > 0 && kind <= 142) || kind === 169) { return node; } - switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 298: - case 247: - return node; + switch (kind) { + case 71: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 145: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 148: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170: @@ -42074,20 +42744,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 174: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 175: @@ -42124,12 +42780,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: @@ -42146,6 +42802,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); case 205: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 207: @@ -42190,6 +42848,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233: @@ -42198,6 +42860,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238: @@ -42222,8 +42886,6 @@ var ts; return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251: @@ -42232,6 +42894,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256: @@ -42256,6 +42920,8 @@ var ts; return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); case 296: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; } @@ -42311,6 +42977,13 @@ var ts; case 147: result = reduceNode(node.expression, cbNode, result); break; + case 148: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -42649,6 +43322,9 @@ var ts; case 296: result = reduceNode(node.expression, cbNode, result); break; + case 297: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -43099,7 +43775,7 @@ var ts; var applicableSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -43888,15 +44564,10 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.text !== serializedIndividual.text) { @@ -44183,7 +44854,12 @@ var ts; } function transformEnumMember(member) { var name = getExpressionForPropertyName(member, false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); @@ -44230,9 +44906,9 @@ var ts; return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ]); + ], currentScope.kind === 265 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -44365,7 +45041,7 @@ var ts; } function visitExportDeclaration(node) { if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; @@ -44675,7 +45351,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -44920,7 +45596,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -44988,19 +45664,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -45127,6 +45798,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -45134,19 +45808,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -45155,12 +45827,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -45392,12 +46059,22 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ @@ -45409,11 +46086,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -45432,7 +46109,7 @@ var ts; var compilerOptions = context.getCompilerOptions(); return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -45870,7 +46547,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -46012,7 +46689,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -46875,12 +47552,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { updated = undefined; @@ -47768,7 +48446,7 @@ var ts; if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -47936,8 +48614,7 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } currentSourceFile = node; @@ -49623,7 +50300,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -49786,9 +50463,9 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return node; @@ -50292,9 +50969,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -50807,9 +51482,9 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 297: - return visitMergeDeclarationMarker(node); case 298: + return visitMergeDeclarationMarker(node); + case 299: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -51100,7 +51775,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -51215,7 +51890,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299); + var enabledSyntaxKindFeatures = new Array(300); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -51273,7 +51948,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } function enableSubstitution(kind) { ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -51443,7 +52118,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -51468,11 +52143,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -51876,8 +52551,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -51890,23 +52564,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -51916,12 +52597,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -51991,7 +52666,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -52219,7 +52894,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -52316,7 +52991,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -52328,12 +53003,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -52347,7 +53016,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -52362,6 +53031,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -52369,15 +53051,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -52398,7 +53087,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -52450,7 +53139,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 148 || + (node.kind === 146 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -52458,7 +53148,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 229 || node.kind === 146) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -52653,6 +53343,11 @@ var ts; write("["); } else { + if (node.kind === 152 && ts.hasModifier(node, 8)) { + write("();"); + writeLine(); + return; + } if (node.kind === 156 || node.kind === 161) { write("new "); } @@ -52911,7 +53606,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { declFileName = referencedFile.fileName; } else { @@ -53674,7 +54369,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -53705,7 +54400,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -53791,7 +54486,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -53867,7 +54564,7 @@ var ts; function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -54067,7 +54764,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -54087,7 +54784,7 @@ var ts; case 97: case 101: case 99: - writeTokenText(kind); + writeTokenNode(node); return; case 177: return emitArrayLiteralExpression(node); @@ -54149,6 +54846,8 @@ var ts; return emitJsxSelfClosingElement(node); case 296: return emitPartiallyEmittedExpression(node); + case 297: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -54174,6 +54873,7 @@ var ts; } function emitIdentifier(node) { write(getTextOfNode(node, false)); + emitTypeArguments(node, node.typeArguments); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -54196,6 +54896,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -54310,7 +55011,9 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65); + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); + } write("}"); } function emitArrayType(node) { @@ -54348,9 +55051,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -54361,8 +55070,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -54375,7 +55089,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); write("}"); } } @@ -54451,7 +55165,7 @@ var ts; } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -54542,7 +55256,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -55221,6 +55935,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272); + } function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -55469,6 +56186,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -55646,7 +56372,9 @@ var ts; if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -55860,14 +56588,17 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -56081,6 +56812,83 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -56130,6 +56938,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -56172,7 +56981,8 @@ var ts; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); if (typeReferences.length) { @@ -56221,7 +57031,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -56254,45 +57065,64 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 && !file.ambientModuleNames.length) { return resolveModuleNamesWorker(moduleNames, containingFile); } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } var unknownModuleNames; var result; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - var isKnownToResolveToAmbientModule = false; + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - result = new Array(moduleNames.length); - unknownModuleNames = moduleNames.slice(0, i); - } - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - unknownModuleNames.push(moduleName); + else { + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; + if (!result) { + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -56301,15 +57131,12 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -56328,67 +57155,73 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0; } var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0; } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - return false; + oldProgram.structureIsReused = 1; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - newSourceFile = oldSourceFile; - } newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -56396,11 +57229,16 @@ var ts; var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2) { + return oldProgram.structureIsReused; } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -56412,8 +57250,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return { @@ -56753,7 +57590,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -56784,7 +57621,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -56825,13 +57661,13 @@ var ts; } break; case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { (ambientModules || (ambientModules = [])).push(moduleName.text); } var body = node.body; @@ -56854,45 +57690,50 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -57028,10 +57869,10 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -57080,7 +57921,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -57177,12 +58018,12 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -57509,7 +58350,6 @@ var ts; case 148: case 261: case 262: - case 264: case 151: case 150: case 152: @@ -57526,9 +58366,11 @@ var ts; case 231: case 163: return 2; + case 264: case 229: - case 232: return 1 | 2; + case 232: + return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -57545,7 +58387,7 @@ var ts; case 238: case 243: case 244: - return 1 | 2 | 4; + return 7; case 265: return 4 | 1; } @@ -57700,7 +58542,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -57715,31 +58557,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -58019,69 +58836,45 @@ var ts; } ts.findContainingList = findContainingList; function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTouchingToken(sourceFile, position, includeJsDocComment, includeItemAtEndPosition) { return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -58089,7 +58882,7 @@ var ts; } } function findTokenOnLeftOfPosition(file, position) { - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -58175,12 +58968,8 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); if (!token) { return false; } @@ -58203,26 +58992,35 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 ? position <= c.end : position < c.end); }); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, false); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { + return kind === 2 || + !(text.charCodeAt(end - 1) === 47 && text.charCodeAt(end - 2) === 42); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); function jsDocPrefix(c) { @@ -58232,7 +59030,7 @@ var ts; } ts.hasDocComment = hasDocComment; function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); + var node = ts.getTokenAtPosition(sourceFile, position, false); if (ts.isToken(node)) { switch (node.kind) { case 104: @@ -58336,6 +59134,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -58376,25 +59177,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119: @@ -58654,8 +59457,8 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; @@ -58677,7 +59480,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -58689,7 +59492,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); @@ -59202,7 +60005,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -59210,8 +60013,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60070,8 +60873,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -60115,7 +60918,7 @@ var ts; return ts.deduplicate(nonRelativeModules); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, false); if (!token) { return undefined; } @@ -60328,7 +61131,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; } @@ -60352,13 +61155,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -60403,8 +61209,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -60461,10 +61267,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -60492,9 +61299,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -60502,16 +61310,20 @@ var ts; if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -60559,10 +61371,10 @@ var ts; var requestJsDocTagName = false; var requestJsDocTag = false; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, false); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -60592,7 +61404,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -60612,7 +61424,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, false); if (contextToken) { if (isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); @@ -60663,6 +61475,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -60693,7 +61506,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; @@ -60735,6 +61548,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -60742,6 +61556,10 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { @@ -60871,12 +61689,14 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174) { @@ -60893,7 +61713,10 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -60904,10 +61727,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -60933,6 +61752,42 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + isMemberCompletion = true; + isNewIdentifierLocation = true; + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32; + break; + } + } + if (!(classElementModifierFlags & 8)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -60961,6 +61816,37 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + case 26: + case 25: + case 18: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61050,7 +61936,7 @@ var ts; containingNodeKind === 231 || isFunction(containingNodeKind); case 115: - return containingNodeKind === 149; + return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: return containingNodeKind === 146 || (contextToken.parent && contextToken.parent.parent && @@ -61063,13 +61949,16 @@ var ts; return containingNodeKind === 242 || containingNodeKind === 246 || containingNodeKind === 240; + case 125: + case 135: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } case 75: case 83: case 109: case 89: case 104: - case 125: - case 135: case 91: case 110: case 76: @@ -61077,6 +61966,10 @@ var ts; case 138: return true; } + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61108,7 +62001,7 @@ var ts; var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -61134,7 +62027,7 @@ var ts; m.kind !== 154) { continue; } - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -61144,17 +62037,51 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + if (m.kind !== 149 && + m.kind !== 151 && + m.kind !== 153 && + m.kind !== 154) { + continue; + } + if (isCurrentlyEditingNode(m)) { + continue; + } + if (ts.hasModifier(m, 8)) { + continue; + } + var mIsStatic = ts.hasModifier(m, 32); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { @@ -61163,6 +62090,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(typeChecker, symbol, location); @@ -61198,6 +62128,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114: + case 113: + case 112: + case 117: + case 115: + case 123: + case 131: + case 125: + case 135: + case 120: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -61213,9 +62164,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingWord(sourceFile, position, true); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -61227,8 +62178,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -61954,6 +62905,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62019,10 +62973,41 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -62044,7 +63029,7 @@ var ts; }); } function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -62072,25 +63057,20 @@ var ts; } } }); - if (sourceFile.flags & 65536) { - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 || decl.kind === 244) { - return decl; + switch (decl.kind) { + case 181: + case 238: + case 244: + return decl; + case 248: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248); - return decl.parent; } function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); @@ -62209,12 +63189,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); - ts.Debug.assert(!!name); - return name; } function skipExportSpecifierSymbol(symbol, checker) { if (symbol.declarations) @@ -62257,12 +63238,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; if (definition) { @@ -62272,39 +63254,44 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position, false); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265) { + return undefined; + } + var checker = program.getTypeChecker(); if (node.parent.kind === 262) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -62314,10 +63301,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -62454,7 +63437,7 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265) { return undefined; @@ -62465,6 +63448,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { if (!options.implementations && node.kind === 9) { @@ -62472,12 +63456,59 @@ var ts; } return undefined; } - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9) { + return false; + } + switch (node.parent.kind) { + case 233: + case 248: + case 238: + case 244: + return true; + case 181: + return ts.isRequireCall(node.parent, false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265: + break; + case 233: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); @@ -62672,7 +63703,11 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; if (!symbolName || !symbolName.length) { return positions; @@ -62697,15 +63732,11 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + var node = ts.getTouchingWord(sourceFile, position, false); + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -62714,30 +63745,30 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, true); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -62751,15 +63782,13 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments || container.jsDoc !== undefined); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (!isValidReferencePosition(referenceLocation, search.text)) { if (!state.implementations && (state.findInStrings && ts.isInString(sourceFile, position) || state.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); @@ -62862,7 +63891,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63092,10 +64121,10 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; - var node = ts.getTouchingWord(sourceFile, position); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || node.kind !== 97) { continue; } @@ -63138,13 +64167,13 @@ var ts; if (searchSpaceNode.kind === 265) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -63153,7 +64182,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || !ts.isThis(node)) { return; } @@ -63188,10 +64217,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -63199,9 +64228,9 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; + var node_7 = ts.getTouchingWord(sourceFile, position, false); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); } @@ -63329,20 +64358,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -63463,7 +64492,7 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -63481,12 +64510,10 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 71 && - (node.parent === declaration || - (declaration.kind === 242 && declaration.parent && declaration.parent.kind === 241))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } if (node.parent.kind === 262) { @@ -63500,27 +64527,17 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -63533,13 +64550,13 @@ var ts; return undefined; } if (type.flags & 65536 && !(type.flags & 16)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -63547,6 +64564,23 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239: + case 237: + return true; + case 242: + return declaration.parent.kind === 241; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -63611,7 +64645,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -63638,7 +64672,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -63707,6 +64741,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -63717,8 +64752,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -63805,7 +64838,7 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -64092,8 +65125,8 @@ var ts; } }); }; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } rawItems = ts.filter(rawItems, function (item) { @@ -64134,16 +65167,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64167,8 +65203,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64201,6 +65238,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64209,8 +65247,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64424,8 +65462,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64503,9 +65541,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64522,7 +65560,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -65742,7 +66780,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 181 || node.parent.kind === 182) { + if (ts.isCallOrNewExpression(node.parent)) { var callExpression = node.parent; if (node.kind === 27 || node.kind === 19) { @@ -66120,7 +67158,7 @@ var ts; } } var callExpressionLike = void 0; - if (location.kind === 181 || location.kind === 182) { + if (ts.isCallOrNewExpression(location)) { callExpressionLike = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -66185,24 +67223,29 @@ var ts; } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { + return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration_1.kind === 152) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; } } } @@ -66266,9 +67309,9 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 145); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; + var decl = ts.getDeclarationOfKind(symbol, 145); + ts.Debug.assert(decl !== undefined); + var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); @@ -66302,7 +67345,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } } } @@ -66548,7 +67591,7 @@ var ts; ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); ts.addRange(diagnostics, program.getOptionsDiagnostics()); } - program.emit(); + program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } @@ -66822,9 +67865,10 @@ var ts; var formatting; (function (formatting) { var FormattingContext = (function () { - function FormattingContext(sourceFile, formattingRequestKind) { + function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; + this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); @@ -67062,7 +68106,7 @@ var ts; this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); @@ -67070,10 +68114,10 @@ var ts; this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -67090,11 +68134,12 @@ var ts; this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); @@ -67102,8 +68147,8 @@ var ts; this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); @@ -67134,6 +68179,41 @@ var ts; this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -67177,7 +68257,25 @@ var ts; this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator + this.NoSpaceBeforeNonNullAssertionOperator, + this.NoSpaceAfterNewKeywordOnConstructorSignature + ]; + this.UserConfigurableRules = [ + this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, + this.SpaceAfterComma, this.NoSpaceAfterComma, + this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, + this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, + this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, + this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, + this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, + this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, + this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, + this.NewLineBeforeOpenBraceInControl, + this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, + this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion ]; this.LowPriorityCommonRules = [ this.NoSpaceBeforeSemicolon, @@ -67188,41 +68286,6 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; @@ -67233,6 +68296,18 @@ var ts; } throw new Error("Unknown rule"); }; + Rules.IsOptionEnabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + }; + Rules.IsOptionDisabled = function (optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + }; + Rules.IsOptionDisabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + }; + Rules.IsOptionEnabledOrUndefined = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + }; Rules.IsForContext = function (context) { return context.contextNode.kind === 214; }; @@ -67448,6 +68523,9 @@ var ts; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 163; }; + Rules.IsConstructorSignatureContext = function (context) { + return context.contextNode.kind === 156; + }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 27 && token.kind !== 29) { return false; @@ -67529,8 +68607,7 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); @@ -67638,27 +68715,14 @@ var ts; (function (formatting) { var Shared; (function (Shared) { - var TokenRangeAccess = (function () { - function TokenRangeAccess(from, to, except) { - this.tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - this.tokens.push(token); - } - } - } - TokenRangeAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenRangeAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0; token <= 142; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -67666,9 +68730,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -67679,18 +68743,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0; token <= 142; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -67698,51 +68758,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92, 93, 142, 118, 126]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43, 44, 52, 51]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 71, 19, 21, 17, 99, 94]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71, 19, 99, 94]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71, 20, 22, 94]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([71, 133, 136, 122, 137, 105, 119]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); + TokenRange.Keywords = TokenRange.FromRange(72, 142); + TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92, 93, 142, 118, 126 + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43, 44, 52, 51 + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8, 71, 19, 21, + 17, 99, 94 + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71, 19, 99, 94 + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71, 20, 22, 94 + ]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71, 133, 136, 122, + 137, 105, 119 + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -67753,6 +68842,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -67768,121 +68859,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -68067,7 +69046,7 @@ var ts; return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -68150,7 +69129,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -68923,9 +69902,7 @@ var ts; if (node.kind === 20) { return -1; } - if (node.parent && (node.parent.kind === 181 || - node.parent.kind === 182) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -69205,7 +70182,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, false); if (nextToken && isSeparator(node, nextToken)) { var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); var nextElement = containingList[index + 1]; @@ -69214,7 +70191,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -69282,7 +70259,7 @@ var ts; } var end = after.getEnd(); if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, false); if (nextToken && isSeparator(after, nextToken)) { var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); @@ -69421,7 +70398,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3, node, sourceFile, writer); @@ -69450,27 +70427,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); var newNode = ts.nodeIsSynthesized(visited) ? visited : (Proxy.prototype = visited, new Proxy()); @@ -69513,6 +70471,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -69579,14 +70547,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -69609,6 +70577,48 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69619,7 +70629,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -69672,13 +70682,14 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); if (token.kind !== 71) { return undefined; } @@ -69750,7 +70761,7 @@ var ts; if (!isStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignatureDeclaration(undefined, undefined, [indexingParameter], typeNode); + var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ @@ -69764,6 +70775,56 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4) { + flags |= 1920; + } + if (meaning & 2) { + flags |= 793064; + } + if (meaning & 1) { + flags |= 107455; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -69778,7 +70839,7 @@ var ts; function getActionForClassLikeMissingAbstractMember(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -69813,7 +70874,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 99) { return undefined; } @@ -69858,7 +70919,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 123) { return undefined; } @@ -69882,7 +70943,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 && ts.isClassLike(classDeclNode))) { return undefined; @@ -69920,7 +70981,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 71) { return undefined; } @@ -69946,126 +71007,131 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); if (token.kind === 21) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, false); } switch (token.kind) { case 71: - switch (token.parent.kind) { - case 226: - switch (token.parent.parent.parent.kind) { - case 214: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215: - return undefined; - case 260: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - case 145: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); - case 242: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); - } - else { - return deleteNodeInList(token.parent); - } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); - } - else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149: case 240: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226: + return deleteVariableDeclaration(token.parent); + case 145: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); + if (!previousToken || previousToken.kind !== 27) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + case 237: + var importEquals = ts.getAncestor(token, 237); + return deleteNode(importEquals); + case 242: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = ts.getAncestor(token, 238); + return deleteNode(importSpec); + } + else { + return deleteNodeInList(token.parent); + } + case 239: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238); + return deleteNode(importDecl); + } + else { + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); + if (nextToken && nextToken.kind === 26) { + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, false); + if (previousToken && previousToken.kind === 26) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215: + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -70096,6 +71162,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -70178,342 +71253,335 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, false, true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, false, true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238) { + return node; } - } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240) { + namespaceImportDeclaration = declaration; } - if (node.kind === 237) { - return node; + else { + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 || statement.kind === 238) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), undefined) + : isNamespaceImport + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -70535,7 +71603,7 @@ var ts; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -70628,7 +71696,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -70677,7 +71745,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -70718,7 +71786,7 @@ var ts; return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { @@ -70736,8 +71804,173 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + if (!(symbol.flags & 4)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + case 187: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + if (arrowFunctionBody.kind === 207) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + default: + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186) { + return undefined; + } + if (node.name.kind !== 71) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : @@ -70788,6 +72021,7 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + ts.Debug.assert(token !== 1); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -70815,27 +72049,31 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143) { + if (ts.isJSDocTag(this)) { + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + } + else if (this.kind >= 143) { + var children_4 = []; ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; var pos_3 = this.pos; var useJSDocScanner_1 = this.kind >= 283 && this.kind <= 293; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, node.pos, useJSDocScanner_1); } - children.push(node); + children_4.push(node); if (!isJSDocTagNode) { pos_3 = node.end; } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, nodes.pos, useJSDocScanner_1); } - children.push(_this.createSyntaxList(nodes)); + children_4.push(_this.createSyntaxList(nodes)); pos_3 = nodes.end; }; if (this.jsDoc) { @@ -70847,11 +72085,14 @@ var ts; pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); + this.addSyntheticNodes(children_4, pos_3, this.end); } ts.scanner.setText(undefined); + this._children = children_4; + } + else { + this._children = ts.emptyArray; } - this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -71116,13 +72357,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -71465,7 +72707,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -71489,9 +72731,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -71667,7 +72906,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -71718,7 +72957,7 @@ var ts; } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -71732,7 +72971,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -71765,11 +73004,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); @@ -71807,7 +73046,7 @@ var ts; } function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, false); if (node === sourceFile) { return; } @@ -71887,7 +73126,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); if (matchKind) { @@ -72017,8 +73256,7 @@ var ts; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -72066,11 +73304,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -72184,20 +73446,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -72582,6 +73844,9 @@ var ts; CommandNames.GetCodeFixes = "getCodeFixes"; CommandNames.GetCodeFixesFull = "getCodeFixes-full"; CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; + CommandNames.GetApplicableRefactors = "getApplicableRefactors"; + CommandNames.GetRefactorCodeActions = "getRefactorCodeActions"; + CommandNames.GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); @@ -72915,6 +74180,15 @@ var ts; _a[CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, + _a[CommandNames.GetApplicableRefactors] = function (request) { + return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); + }, + _a[CommandNames.GetRefactorCodeActions] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, true)); + }, + _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { + return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + }, _a)); this.host = opts.host; this.cancellationToken = opts.cancellationToken; @@ -72945,7 +74219,8 @@ var ts; throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); @@ -73881,6 +75156,47 @@ var ts; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); }; + Session.prototype.isLocation = function (locationOrSpan) { + return locationOrSpan.line !== undefined; + }; + Session.prototype.extractPositionAndRange = function (args, scriptInfo) { + var position = undefined; + var textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } + else { + var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; + textRange = { pos: startPosition, end: endPosition }; + } + return { position: position, textRange: textRange }; + function getPosition(loc) { + return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + }; + Session.prototype.getApplicableRefactors = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + return project.getLanguageService().getApplicableRefactors(file, position || textRange); + }; + Session.prototype.getRefactorCodeActions = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; + var result = project.getLanguageService().getRefactorCodeActions(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactorName); + if (simplifiedResult) { + return { + actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + }; + } + else { + return { + actions: result + }; + } + }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; if (args.errorCodes.length === 0) { @@ -73888,8 +75204,7 @@ var ts; } var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = getStartPosition(); - var endPosition = getEndPosition(); + var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); if (!codeActions) { @@ -73901,12 +75216,24 @@ var ts; else { return codeActions; } - function getStartPosition() { - return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + }; + Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { + var startPosition = undefined, endPosition = undefined; + if (args.startPosition !== undefined) { + startPosition = args.startPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; + } + else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition: startPosition, endPosition: endPosition }; }; Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { var _this = this; @@ -76213,7 +77540,7 @@ var ts; var oldProgram = this.program; this.program = this.languageService.getProgram(); var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { hasChanges = true; if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -76470,6 +77797,11 @@ var ts; return; } var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.allowLocalPluginLoads) { + var local = ts.getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); + searchPaths.unshift(local); + } if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -76854,6 +78186,7 @@ var ts; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); @@ -78429,6 +79762,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 2f11d458e20..8efe0a1e3b4 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -359,9 +359,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -474,6 +475,10 @@ declare namespace ts { type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ text: string; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; @@ -491,9 +496,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +511,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +519,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +532,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +544,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +553,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +575,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +597,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +605,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +957,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1016,7 +1023,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1076,6 +1083,13 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1197,7 +1211,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1224,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1252,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1311,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1344,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1481,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1706,11 +1720,11 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1720,38 +1734,48 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1912,18 +1936,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1935,15 +1959,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } enum ObjectFlags { Class = 1, @@ -1988,7 +2014,7 @@ declare namespace ts { */ interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -2024,7 +2050,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { @@ -2059,9 +2085,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2329,6 +2355,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2611,14 +2638,14 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2695,6 +2722,7 @@ declare namespace ts { * @returns The unescaped identifier text. */ function unescapeIdentifier(identifier: string): string; + function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; } declare namespace ts { /** @@ -2709,6 +2737,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -2727,58 +2756,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2786,6 +2776,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2827,7 +2856,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2847,16 +2876,15 @@ 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 createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2888,10 +2916,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2900,6 +2937,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2930,20 +2969,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2976,6 +3015,8 @@ declare namespace ts { */ function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -3040,11 +3081,11 @@ declare namespace ts { /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; /** * Sets the constant value to emit for an expression. */ - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; /** * Adds an EmitHelper to a node. */ @@ -3069,17 +3110,13 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** Array that is only intended to be pushed to, never read. */ - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -3218,6 +3255,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -3246,9 +3284,10 @@ declare namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3422,6 +3461,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3492,6 +3533,10 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -4006,6 +4051,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; diff --git a/lib/typescript.js b/lib/typescript.js index 4fe0eb9bf25..a59610eae73 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -365,10 +365,11 @@ var ts; // Transformation nodes SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -512,6 +513,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); /** Return code used by getEmitOutput function to indicate status of the function */ var ExitStatus; (function (ExitStatus) { @@ -527,12 +535,23 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -677,6 +696,12 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -751,7 +776,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -761,7 +786,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; @@ -770,7 +795,7 @@ var ts; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; @@ -1119,6 +1144,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1138,17 +1164,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1450,12 +1481,6 @@ var ts; return undefined; } ts.forEach = forEach; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1477,6 +1502,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1704,6 +1738,35 @@ var ts; return result; } ts.flatMap = flatMap; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2881,6 +2944,11 @@ var ts; } ts.startsWith = startsWith; /* @internal */ + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -4058,6 +4126,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -4165,7 +4234,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -4360,6 +4429,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4655,6 +4732,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4700,6 +4778,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4781,6 +4861,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -5443,9 +5526,10 @@ var ts; ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6654,9 +6738,7 @@ var ts; ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -6849,28 +6931,30 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8 /* NumericLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -7099,10 +7183,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 /* EnumDeclaration */ && isConst(node); } @@ -7382,6 +7462,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151 /* MethodDeclaration */: @@ -7638,6 +7727,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183 /* TaggedTemplateExpression */) { return node.tag; @@ -8074,9 +8167,6 @@ var ts; } ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } var func = param.parent; var tags = getJSDocTags(func, 286 /* JSDocParameterTag */); if (!param.name) { @@ -8098,6 +8188,19 @@ var ts; } } ts.getJSDocParameterTags = getJSDocParameterTags; + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterFromJSDoc(node) { + var name = node.parameterName.text; + var grandParent = node.parent.parent; + ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */); + if (!isFunctionLike(grandParent)) { + return undefined; + } + return ts.find(grandParent.parameters, function (p) { + return p.name.kind === 71 /* Identifier */ && p.name.text === name; + }); + } + ts.getParameterFromJSDoc = getParameterFromJSDoc; function getJSDocType(node) { var tag = getFirstJSDocTag(node, 288 /* JSDocTypeTag */); if (!tag && node.kind === 146 /* Parameter */) { @@ -8230,19 +8333,14 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 71 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { - return false; + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 /* ImportSpecifier */ || parent.kind === 246 /* ExportSpecifier */) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { @@ -8357,21 +8455,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -8399,12 +8495,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8457,7 +8554,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -8740,6 +8838,8 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; + case 297 /* CommaListExpression */: + return 0; default: return -1; } @@ -8853,14 +8953,15 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -8949,7 +9050,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -9015,7 +9116,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; /** @@ -9579,13 +9680,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0 /* CarriageReturnLineFeed */) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; } - else if (options.newLine === 1 /* LineFeed */) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -9913,10 +10014,6 @@ var ts; return node.kind === 71 /* Identifier */; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; @@ -9989,9 +10086,20 @@ var ts; || kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */ || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */; + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 /* ConstructSignature */ + || kind === 155 /* CallSignature */ + || kind === 148 /* PropertySignature */ + || kind === 150 /* MethodSignature */ + || kind === 157 /* IndexSignature */ + || kind === 247 /* MissingDeclaration */; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 /* PropertyAssignment */ @@ -10209,6 +10317,7 @@ var ts; || kind === 198 /* SpreadElement */ || kind === 202 /* AsExpression */ || kind === 200 /* OmittedExpression */ + || kind === 297 /* CommaListExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -10297,6 +10406,10 @@ var ts; return node.kind === 237 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239 /* ImportClause */; } @@ -10319,6 +10432,10 @@ var ts; return node.kind === 246 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; } @@ -10390,8 +10507,8 @@ var ts; || kind === 213 /* WhileStatement */ || kind === 220 /* WithStatement */ || kind === 295 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + || kind === 299 /* EndOfDeclarationMarker */ + || kind === 298 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -10517,6 +10634,49 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10891,6 +11051,27 @@ var ts; return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; })(ts || (ts = {})); /// /// @@ -10983,16 +11164,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - // Identifiers - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable) { @@ -11087,240 +11276,13 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - // Type Elements - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - // Types - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173 /* LiteralType */); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159 /* TypeReference */); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158 /* TypePredicate */); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162 /* TypeQuery */); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164 /* ArrayType */); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163 /* TypeLiteral */); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165 /* TupleType */); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172 /* MappedType */); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170 /* TypeOperator */); - typeOperatorNode.operator = 127 /* KeyOfKeyword */; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171 /* IndexedAccessType */); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; - // Type Declarations + // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145 /* TypeParameter */); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -11331,44 +11293,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - // Signature elements - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148 /* PropertySignature */); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157 /* IndexSignature */); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; - // Signature elements function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146 /* Parameter */); node.decorators = asNodeArray(decorators); @@ -11405,7 +11329,27 @@ var ts; : node; } ts.updateDecorator = updateDecorator; - // Type members + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); @@ -11427,7 +11371,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -11440,7 +11401,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -11450,7 +11411,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11518,6 +11479,251 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164 /* ArrayType */); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170 /* TypeOperator */); + node.operator = 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174 /* ObjectBindingPattern */); @@ -11565,9 +11771,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11580,9 +11785,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11632,9 +11836,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11824,10 +12028,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11954,6 +12158,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205 /* TemplateSpan */); @@ -11969,6 +12186,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { var block = createSynthesizedNode(207 /* Block */); @@ -11979,7 +12200,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11999,35 +12220,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209 /* EmptyStatement */); } @@ -12246,6 +12438,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); @@ -12294,6 +12519,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); @@ -12314,7 +12581,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233 /* ModuleDeclaration */); - node.flags |= flags; + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -12355,6 +12622,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); @@ -12385,7 +12664,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12573,19 +12853,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254 /* JsxAttributes */); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253 /* JsxAttribute */); node.name = name; @@ -12600,6 +12867,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); node.expression = expression; @@ -12626,20 +12905,6 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; // Clauses - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12648,10 +12913,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12661,12 +12926,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260 /* CatchClause */); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12675,10 +12952,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; // Property assignments @@ -12691,10 +12968,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12705,10 +12982,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12718,10 +12995,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; // Enum @@ -12833,7 +13109,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12845,7 +13121,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12874,6 +13150,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266 /* Bundle */); node.sourceFiles = sourceFiles; @@ -13250,7 +13549,25 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // Compound nodes + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -13512,7 +13829,11 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13686,9 +14007,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13846,16 +14168,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -14131,6 +14443,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; /** * Clones a series of not-emitted expressions with a new inner expression. * @@ -14311,7 +14651,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15079,6 +15419,8 @@ var ts; return visitNode(cbNode, node.expression); case 247 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 297 /* CommaListExpression */: + return visitNodes(cbNodes, node.elements); case 249 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -20465,6 +20807,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -21452,7 +21796,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -21480,7 +21824,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -21517,12 +21861,13 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21530,7 +21875,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21548,18 +21893,9 @@ var ts; case 243 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; case 194 /* BinaryExpression */: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2 /* ModuleExports */: - // module.exports = ... - return "export="; - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - // exports.x = ... or this.y = ... - return node.left.name.text; - case 3 /* PrototypeProperty */: - // className.prototype.methodName = ... - return node.left.expression.name.text; + if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; @@ -21674,9 +22010,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -21711,6 +22047,8 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (node.kind === 290 /* JSDocTypedefTag */) + ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. var isJSDocTypedefInJSDocNamespace = node.kind === 290 /* JSDocTypedefTag */ && node.name && node.name.kind === 71 /* Identifier */ && @@ -21869,9 +22207,7 @@ var ts; // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } + ts.forEach(node.jsDoc, bind); if (checkUnreachable(node)) { bindEachChild(node); return; @@ -23057,9 +23393,7 @@ var ts; // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } + bindJSDocTypedefTagIfAny(node); // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible // destination symbol tables are: @@ -23141,7 +23475,7 @@ var ts; // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. - if (node.isInJSDocNamespace) { + if (ts.isInJavaScriptFile(node) && node.isInJSDocNamespace) { var parentNode = node.parent; while (parentNode && parentNode.kind !== 290 /* JSDocTypedefTag */) { parentNode = parentNode.parent; @@ -23211,10 +23545,7 @@ var ts; return bindVariableDeclarationOrBindingElement(node); case 149 /* PropertyDeclaration */: case 148 /* PropertySignature */: - case 276 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - case 291 /* JSDocPropertyTag */: - return bindJSDocProperty(node); + return bindPropertyWorker(node); case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); @@ -23256,13 +23587,10 @@ var ts; return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); case 160 /* FunctionType */: case 161 /* ConstructorType */: - case 279 /* JSDocFunctionType */: return bindFunctionOrConstructorType(node); case 163 /* TypeLiteral */: case 172 /* MappedType */: - case 292 /* JSDocTypeLiteral */: - case 275 /* JSDocRecordType */: - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + return bindAnonymousTypeWorker(node); case 178 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 186 /* FunctionExpression */: @@ -23281,11 +23609,6 @@ var ts; return bindClassLikeDeclaration(node); case 230 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 290 /* JSDocTypedefTag */: - if (!node.fullName || node.fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - } - break; case 231 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); case 232 /* EnumDeclaration */: @@ -23321,8 +23644,37 @@ var ts; // falls through case 234 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); + default: + if (ts.isInJavaScriptFile(node)) + return bindJSDocWorker(node); } } + function bindJSDocWorker(node) { + switch (node.kind) { + case 276 /* JSDocRecordMember */: + return bindPropertyWorker(node); + case 291 /* JSDocPropertyTag */: + return declareSymbolAndAddToSymbolTable(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 279 /* JSDocFunctionType */: + return bindFunctionOrConstructorType(node); + case 292 /* JSDocTypeLiteral */: + case 275 /* JSDocRecordType */: + return bindAnonymousTypeWorker(node); + case 290 /* JSDocTypedefTag */: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71 /* Identifier */) { + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; if (parameterName && parameterName.kind === 71 /* Identifier */) { @@ -23592,7 +23944,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -23611,7 +23963,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23626,7 +23978,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23639,10 +23991,8 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { node.flowNode = currentFlow; @@ -23651,9 +24001,6 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4 /* Property */, 0 /* PropertyExcludes */); - } // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); @@ -24526,13 +24873,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -24860,6 +25205,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25062,13 +25409,24 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -25099,7 +25457,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -25462,6 +25819,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -25613,13 +25971,16 @@ var ts; // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -25702,11 +26063,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -25972,16 +26335,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26063,9 +26426,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -26073,7 +26433,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -26109,7 +26469,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26205,7 +26566,11 @@ var ts; // 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 // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; var propertyWithInvalidInitializer; @@ -26215,7 +26580,7 @@ var ts; loop: while (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 = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { // symbol lookup restrictions for function-like declarations @@ -26286,12 +26651,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { break loop; } break; case 232 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; @@ -26306,7 +26671,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -26316,7 +26681,7 @@ var ts; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -26351,7 +26716,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -26412,7 +26777,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -26422,7 +26787,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -26541,6 +26916,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -26573,13 +26952,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -26595,7 +26974,7 @@ var ts; if (node.kind === 237 /* ImportEqualsDeclaration */) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238 /* ImportDeclaration */; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -26719,10 +27098,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); @@ -26738,7 +27117,7 @@ var ts; case 242 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 243 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236 /* NamespaceExportDeclaration */: @@ -26887,7 +27266,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26909,6 +27288,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; @@ -26978,7 +27362,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -27128,7 +27511,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32 /* StringLiteral */, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started @@ -27458,34 +27841,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -27495,15 +27903,14 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } if (type.flags & 1 /* Any */) { @@ -27518,23 +27925,25 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 16 /* Enum */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + } + if (type.flags & 272 /* EnumLike */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256 /* EnumLiteral */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & 1024 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } @@ -27554,8 +27963,8 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -27566,39 +27975,31 @@ var ts; ts.Debug.assert(!!(type.flags & 32768 /* Object */)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3 /* ClassOrInterface */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - // TODO(aozgaa): handle type arguments. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & 16384 /* TypeParameter */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536 /* Union */) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166 /* UnionType */, unionTypeNodes); + if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { + var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072 /* Intersection */) { - return ts.createUnionOrIntersectionTypeNode(167 /* IntersectionType */, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); // The type is an object literal type. @@ -27606,35 +28007,23 @@ var ts; } if (type.flags & 262144 /* Index */) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -27643,14 +28032,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); } else if (ts.contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27696,41 +28085,53 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(/*members*/ undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -27738,7 +28139,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27751,48 +28152,72 @@ var ts; // 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)) { - var qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, /*right*/ undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71 /* Identifier */) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71 /* Identifier */) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); } var properties = resolvedType.properties; if (!properties) { @@ -27801,86 +28226,131 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 136 /* StringKeyword */ : 133 /* NumberKeyword */); - var name = ts.getNameFromIndexInfo(indexInfo); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration( + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - // TODO(aozgaa): In the future, check initializer accessibility. - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24 /* DotDotDotToken */), - // Clone name to remove trivia. - ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55 /* QuestionToken */), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048 /* Undefined */); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0 /* None */, /*endOfChain*/ true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -27888,19 +28358,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -27909,20 +28378,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -27954,28 +28413,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -27993,12 +28453,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -28034,13 +28496,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28097,7 +28560,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -28180,12 +28643,17 @@ var ts; else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -28541,7 +29009,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -28808,10 +29276,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246 /* ExportSpecifier */) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -28954,7 +29419,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -29070,7 +29535,7 @@ var ts; return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -29173,6 +29638,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : @@ -29189,17 +29655,25 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536 /* JavaScriptFile */) { - // If there is a JSDoc type, use it - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding @@ -29449,7 +29923,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; } } } @@ -29512,7 +29986,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -29711,6 +30185,7 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && @@ -29718,7 +30193,7 @@ var ts; // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; @@ -29902,77 +30377,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 /* NumericLiteral */ || + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 71 /* Identifier */ && !!symbol.exports.get(expr.text); + expr.kind === 71 /* Identifier */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256 /* EnumLiteral */); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536 /* Union */; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 65536 /* Union */) { + enumType_1.flags |= 256 /* EnumLiteral */; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -30219,7 +30697,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -30306,8 +30784,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -30481,7 +30959,7 @@ var ts; // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); @@ -30613,6 +31091,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190 /* Primitive */) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : @@ -30674,8 +31173,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -30731,7 +31230,7 @@ var ts; var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : @@ -30746,12 +31245,12 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -30823,7 +31322,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -31231,8 +31730,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -31367,8 +31867,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_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -31399,7 +31899,7 @@ var ts; return ts.length(type.target.typeParameters); } // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -31414,7 +31914,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -31437,7 +31937,7 @@ var ts; // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -31449,7 +31949,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -31489,14 +31988,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 /* Value */ && node.kind === 277 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In @@ -31559,10 +32059,7 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. @@ -31571,6 +32068,9 @@ var ts; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -31812,14 +32312,14 @@ 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, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31827,8 +32327,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -31959,8 +32459,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 addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -32024,9 +32524,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -32056,12 +32556,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? - indexType.text : + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -32076,11 +32576,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { @@ -32105,7 +32605,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -32258,7 +32758,7 @@ var ts; var rightProp = _a[_i]; // we approximate own properties as non-methods plus methods that are inside the object literal var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -32275,11 +32775,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { + if (rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -32306,15 +32806,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32325,11 +32826,17 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -32593,7 +33100,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { var links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases @@ -33087,29 +33594,27 @@ var ts; type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8 /* EnumMember */) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33120,42 +33625,50 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + if (t & 1 /* Any */ || s & 8192 /* Never */) return true; - if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) + if (s & 262178 /* StringLike */ && t & 2 /* String */) return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + if (s & 84 /* NumberLike */ && t & 4 /* Number */) return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { + if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 /* Literal */ && t & 224 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) return true; - if (source.flags & 32768 /* Object */ && target.flags & 16777216 /* NonPrimitive */) + if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) + if (s & 1 /* Any */) return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -33378,29 +33891,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33789,10 +34279,10 @@ var ts; } } else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -33901,24 +34391,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34038,7 +34542,7 @@ var ts; // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6 /* Synthetic */) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -34065,13 +34569,13 @@ var ts; } // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is the constructor type for an abstract class @@ -34120,8 +34624,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -34215,8 +34719,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -34224,8 +34728,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34251,7 +34755,7 @@ var ts; return getUnionType(types, /*subtypeReduction*/ true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -34299,27 +34803,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -34331,8 +34835,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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -34342,35 +34846,35 @@ var ts; // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : type.flags & 7406 /* PossiblyFalsy */; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) - types.push(voidType); - if (flags & 2048 /* Undefined */) - types.push(undefinedType); - if (flags & 4096 /* Null */) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 /* String */ ? emptyStringType : + type.flags & 4 /* Number */ ? zeroType : + type.flags & 8 /* Boolean */ || type === falseType ? falseType : + type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & 32 /* StringLiteral */ && type.value === "" || + type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + return missing === 0 ? type : + missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } @@ -34537,7 +35041,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -34622,7 +35126,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -34655,20 +35159,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -34683,7 +35177,7 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -34800,26 +35294,29 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768 /* Object */) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 32768 /* Object */ && + !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -34908,8 +35405,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35005,7 +35502,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35018,11 +35515,13 @@ var ts; // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35091,7 +35590,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } @@ -35154,8 +35653,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -35173,15 +35672,16 @@ var ts; return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type.text === "0"; + if (flags & 64 /* NumberLiteral */) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; @@ -35388,7 +35888,7 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -35414,8 +35914,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35495,8 +35995,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35527,7 +36027,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -35553,7 +36053,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -35695,7 +36195,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36202,6 +36702,26 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 /* PropertyAccessExpression */ || + parent.kind === 181 /* CallExpression */ && parent.expression === node || + parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + } + function getDeclaredOrApparentType(symbol, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36268,7 +36788,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36309,7 +36829,7 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048 /* Undefined */); + getNullableType(type, 2048 /* Undefined */); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -36317,7 +36837,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37214,8 +37734,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -37329,7 +37849,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -37367,7 +37887,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -37518,6 +38038,8 @@ var ts; if (spread.flags & 32768 /* Object */) { // only set the symbol and flags if this is a (fresh) object type spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; spread.symbol = node.symbol; } return spread; @@ -37596,6 +38118,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37613,6 +38139,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37622,39 +38151,39 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. if (child.kind === 10 /* JsxText */) { @@ -37666,11 +38195,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37681,7 +38210,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37689,8 +38223,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37768,7 +38301,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37820,6 +38364,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37840,6 +38398,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37878,6 +38437,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -37947,7 +38507,7 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -38152,6 +38712,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38180,7 +38768,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38200,29 +38801,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; - } - if (getCheckFlags(s) & 6 /* Synthetic */) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : - 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216 /* Prototype */) { - return 4 /* Public */ | 32 /* Static */; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); } /** * Check whether the requested property access is valid. @@ -38233,11 +38816,11 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? node.name : node.right; - if (getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 256 /* 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; @@ -38335,42 +38918,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (getCheckFlags(prop) & 1 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -38407,7 +38954,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -38426,6 +38973,126 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455 /* Value */); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -38548,7 +39215,16 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183 /* TaggedTemplateExpression */) { checkExpression(node.template); } @@ -38579,8 +39255,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -38688,7 +39364,7 @@ var ts; // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -39059,7 +39735,7 @@ var ts; case 71 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { @@ -39169,7 +39845,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; var isDecorator = node.kind === 147 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -39199,7 +39875,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -39300,7 +39976,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -39308,14 +39984,45 @@ var ts; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } // 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 that anySignature. @@ -39323,8 +40030,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -39334,14 +40041,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -39509,7 +40208,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39676,8 +40375,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -39854,7 +40553,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return getNullableType(type, 2048 /* Undefined */); } } return type; @@ -39920,11 +40619,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -40055,7 +40754,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40251,7 +40950,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40278,7 +40977,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { 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); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40291,7 +40990,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -40304,8 +41003,8 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || - symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */); @@ -40392,7 +41091,7 @@ var ts; return silentNeverType; } if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37 /* PlusToken */: @@ -40439,8 +41138,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40457,8 +41156,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -40467,8 +41166,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -40513,7 +41212,7 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { @@ -40808,7 +41507,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; @@ -40868,7 +41567,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? @@ -40961,12 +41660,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41012,9 +41714,9 @@ var ts; } switch (node.kind) { case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; case 86 /* FalseKeyword */: @@ -41079,7 +41781,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); } return false; } @@ -41424,17 +42126,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41457,7 +42160,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41476,7 +42179,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41595,7 +42298,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41683,7 +42386,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41840,7 +42544,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -41883,7 +42587,7 @@ var ts; } // Check if we're indexing with a numeric type and the object type is a generic // type with a constraint that has a numeric index signature. - if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 340 /* NumberLike */)) { + if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 84 /* NumberLike */)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { return type; @@ -41943,16 +42647,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41963,7 +42667,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42087,7 +42791,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42101,8 +42805,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42160,12 +42864,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42480,7 +43185,9 @@ var ts; * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -42490,6 +43197,57 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167 /* IntersectionType */: + case 166 /* UnionType */: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -42520,7 +43278,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -42529,15 +43287,15 @@ var ts; case 154 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149 /* PropertyDeclaration */: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146 /* Parameter */: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -42671,15 +43429,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42759,7 +43518,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42827,7 +43586,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42841,7 +43600,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43107,7 +43866,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43222,11 +43981,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43609,7 +44371,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43831,13 +44593,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44076,7 +44841,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -44109,7 +44874,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -44132,15 +44897,11 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; @@ -44160,7 +44921,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44247,97 +45008,88 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); - var autoValue = 0; // set to undefined when enum member is non-constant - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384 /* EnumValuesComputed */; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192 /* PrefixUnaryExpression */: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + 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); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192 /* PrefixUnaryExpression */: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37 /* PlusToken */: return value_1; case 38 /* MinusToken */: return -value_1; case 52 /* TildeToken */: return ~value_1; } - return undefined; - case 194 /* BinaryExpression */: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49 /* BarToken */: return left | right; case 48 /* AmpersandToken */: return left & right; case 46 /* GreaterThanGreaterThanToken */: return left >> right; @@ -44350,81 +45102,53 @@ var ts; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; } - return undefined; - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(e); - return +e.text; - case 185 /* ParenthesizedExpression */: - return evalConstant(e.expression); - case 71 /* Identifier */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71 /* Identifier */) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = expr.kind === 179 /* PropertyAccessExpression */ ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180 /* ElementAccessExpression */) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9 /* StringLiteral */) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - var current = expression; - while (current) { - if (current.kind === 71 /* Identifier */) { - break; - } - else if (current.kind === 179 /* PropertyAccessExpression */) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8 /* EnumMember */)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 /* Identifier */ || + node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9 /* StringLiteral */; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -44455,7 +45179,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -44714,6 +45438,10 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === 246 /* ExportSpecifier */ && compilerOptions.isolatedModules && !(target.flags & 107455 /* Value */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -45389,6 +46117,10 @@ var ts; return entityNameSymbol; } } + if (entityName.parent.kind === 286 /* JSDocParameterTag */) { + var parameter = ts.getParameterFromJSDoc(entityName.parent); + return parameter && parameter.symbol; + } if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { // Missing entity name. @@ -45436,7 +46168,7 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -45564,7 +46296,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -45654,16 +46386,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { @@ -45981,7 +46713,7 @@ var ts; else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178 /* StringLike */)) { @@ -46010,7 +46742,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096 /* AddUndefined */) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -46022,15 +46754,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46116,7 +46839,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46284,7 +47006,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46311,9 +47033,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -47419,6 +48142,19 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + if (name.parent.propertyName) { + return true; + } + // falls through + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); /// /// @@ -47556,53 +48292,63 @@ var ts; if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { return node; } - switch (node.kind) { - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 298 /* EndOfDeclarationMarker */: - case 247 /* MissingDeclaration */: - // No need to visit nodes with no children. - return node; + switch (kind) { // Names + case 71 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - // Signatures and Signature Elements - case 160 /* FunctionType */: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155 /* CallSignature */: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150 /* MethodSignature */: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157 /* IndexSignature */: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Signature elements + case 145 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 148 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 159 /* TypeReference */: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 158 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163 /* TypeLiteral */: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167 /* IntersectionType */: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170 /* TypeOperator */: @@ -47613,22 +48359,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - // Type Declarations - case 145 /* TypeParameter */: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - // Type members - case 148 /* PropertySignature */: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* MethodDeclaration */: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); // Binding patterns case 174 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); @@ -47667,12 +48397,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: @@ -47689,6 +48419,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc case 205 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); @@ -47735,6 +48467,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233 /* ModuleDeclaration */: @@ -47743,6 +48479,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238 /* ImportDeclaration */: @@ -47769,8 +48507,6 @@ var ts; // JSX case 249 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxAttributes */: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251 /* JsxOpeningElement */: @@ -47779,6 +48515,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256 /* JsxExpression */: @@ -47808,7 +48546,10 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: + // No need to visit nodes with no children. return node; } } @@ -47884,6 +48625,13 @@ var ts; result = reduceNode(node.expression, cbNode, result); break; // Type member + case 148 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -48234,6 +48982,9 @@ var ts; case 296 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; + case 297 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -48856,7 +49607,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -50275,21 +51026,17 @@ var ts; return ts.createIdentifier("Object"); } function serializeUnionOrIntersectionType(node) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || @@ -50819,7 +51566,12 @@ var ts; // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -50894,10 +51646,12 @@ var ts; * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { - // Emit a variable statement for the module. - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ]); + ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -51154,7 +51908,7 @@ var ts; function visitExportDeclaration(node) { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -51583,7 +52337,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -51920,7 +52674,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -51988,21 +52742,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52152,6 +52900,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52159,24 +52910,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52187,13 +52935,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52479,12 +53221,22 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; @@ -52498,11 +53250,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -52532,7 +53284,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -53017,7 +53769,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -53224,7 +53976,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -54502,12 +55254,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26 /* CommaToken */, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -55842,7 +56595,7 @@ var ts; if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -56276,8 +57029,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } currentSourceFile = node; @@ -58730,7 +59482,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -59025,9 +59777,9 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: // This visitor does not descend into the tree, as export/import statements @@ -59826,9 +60578,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60716,9 +61466,9 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -61200,7 +61950,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -61363,7 +62113,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(300 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -61428,7 +62178,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** * Enables expression substitutions in the pretty printer for the provided SyntaxKind. @@ -62377,7 +63127,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62413,11 +63163,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62844,12 +63594,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62862,24 +63611,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62891,12 +63646,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62969,7 +63718,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63206,7 +63955,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -63305,7 +64054,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63317,12 +64066,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63339,7 +64082,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63354,6 +64097,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63361,15 +64117,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63390,7 +64153,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -63449,7 +64212,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) { + else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || + (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -63458,7 +64222,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -63668,6 +64432,11 @@ var ts; write("["); } else { + if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { write("new "); @@ -63974,7 +64743,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } @@ -64158,7 +64927,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -64195,7 +64964,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -64283,7 +65052,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -64362,7 +65133,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -64580,7 +65351,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -64603,7 +65374,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions case 177 /* ArrayLiteralExpression */: @@ -64668,6 +65439,8 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* CommaListExpression */: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -64706,6 +65479,7 @@ var ts; // function emitIdentifier(node) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // // Names @@ -64734,6 +65508,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -64854,7 +65629,10 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65 /* TypeLiteralMembers */); + // If the literal is empty, do not add spaces between braces. + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); + } write("}"); } function emitArrayType(node) { @@ -64892,9 +65670,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -64905,8 +65689,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -64922,7 +65711,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); + emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); write("}"); } } @@ -65006,7 +65795,7 @@ var ts; // check if constant enum value is integer var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -65109,7 +65898,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -65837,6 +66626,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272 /* CommaListElements */); + } /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -66118,6 +66910,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -66300,7 +67101,9 @@ var ts; if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -66580,14 +67383,17 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -66814,6 +67620,90 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + // 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) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + 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. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -66863,6 +67753,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -66919,7 +67810,8 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); @@ -66978,7 +67870,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67016,76 +67909,100 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { - // if old program state is not supplied and file does not contain locally defined ambient modules - // then the best we can do is fallback to the default logic + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile); } - // at this point we know that either + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occured during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules - // OR // - old program state is available - // OR - // - both of items above - // With this it is possible that we can tell how some module names from the initial list will be resolved - // without doing actual resolution (in particular if some name was resolved to ambient module). - // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` - // since we don't want to resolve them again. - // this is a list of modules for which we cannot predict resolution so they should be actually resolved + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ var unknownModuleNames; - // this is a list of combined results assembles from predicted and resolved results. - // Order in this list matches the order in the original list of module names `moduleNames` which is important - // so later we can split results to resolutions of modules and resolutions of module augmentations. + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ var result; - // a transient placeholder that is used to mark predicted resolution in the result list + /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // module name is known to be resolved to ambient module if - // - module name is contained in the list of ambient modules that are locally declared in the file - // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // If we want to reuse resolutions more aggressively, we can refine this to check for whether the + // text of the corresponding modulenames has changed. + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file // (so the same module declaration will land in the new program) - var isKnownToResolveToAmbientModule = false; + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - // found a first module name for which result can be prediced - // this means that this module name should not be passed to `resolveModuleNamesWorker`. - // We'll use a separate list for module names that are definitely unknown. - result = new Array(moduleNames.length); - // copy all module names that appear before the current one in the list - // since they are known to be unknown - unknownModuleNames = moduleNames.slice(0, i); - } - // mark prediced resolution in the result list - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - // found unknown module name and we are already using separate list for those - add it to the list - unknownModuleNames.push(moduleName); + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - // we've looked throught the list but have not seen any predicted resolution - // use default logic - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; - // combine results of resolutions and predicted results + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -67094,16 +68011,15 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { // module used to be resolved to file - ignore it return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -67123,84 +68039,90 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0 /* Not */; } // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); // there is an old program, check if we can reuse its structure var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { + // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check tripleslash references if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - // file has no changes - use it as is - newSourceFile = oldSourceFile; - } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); // try to verify results of module resolution for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -67209,12 +68131,16 @@ var ts; // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { @@ -67227,8 +68153,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return { @@ -67616,7 +68541,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -67647,7 +68572,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -67694,7 +68618,7 @@ var ts; } break; case 233 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -67705,7 +68629,7 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -67734,45 +68658,52 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -67925,11 +68856,11 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -67986,7 +68917,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -68084,12 +69015,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -69266,57 +70197,37 @@ var ts; * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; + } + if (exclude) { + json.exclude = exclude; + } + if (files) { + json.files = files; + } + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; + } + return options; + })(); + options = ts.extend(existingOptions, options); + options.configFilePath = configFileName; // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } - options = ts.extend(existingOptions, options); - options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -69326,39 +70237,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -69389,9 +70268,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -69409,9 +70285,73 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, // Usually a string. + host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -70046,7 +70986,6 @@ var ts; case 148 /* PropertySignature */: case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: - case 264 /* EnumMember */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: case 152 /* Constructor */: @@ -70063,9 +71002,11 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 264 /* EnumMember */: case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; + case 232 /* EnumDeclaration */: + return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -70082,7 +71023,7 @@ var ts; case 238 /* ImportDeclaration */: case 243 /* ExportAssignment */: case 244 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; // An external module can be a Value case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; @@ -70241,7 +71182,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -70256,36 +71197,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -70590,78 +71501,53 @@ var ts; * position >= start and (position < end or (position === end && token is keyword or identifier)) */ function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; /* Gets the token whose text has range [start, end) and position >= start * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) */ function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTouchingToken(sourceFile, position, includeJsDocComment, includeItemAtEndPosition) { return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { // exit early return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } // find the child that contains 'position' - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -70679,7 +71565,7 @@ var ts; function findTokenOnLeftOfPosition(file, position) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -70788,15 +71674,11 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; /** * returns true if the position is in between the open and close elements of an JSX expression. */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return false; } @@ -70825,18 +71707,32 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -70847,18 +71743,16 @@ var ts; // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + return kind === 2 /* SingleLineCommentTrivia */ || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === 47 /* slash */ && text.charCodeAt(end - 2) === 42 /* asterisk */); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); @@ -70872,7 +71766,7 @@ var ts; * Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); + var node = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (ts.isToken(node)) { switch (node.kind) { case 104 /* VarKeyword */: @@ -70979,6 +71873,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -71027,25 +71924,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119 /* AnyKeyword */: @@ -71326,8 +72225,8 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; @@ -71350,7 +72249,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -71422,7 +72321,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -71431,8 +72330,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72441,8 +73340,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -72491,7 +73390,7 @@ var ts; return ts.deduplicate(nonRelativeModules); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return undefined; } @@ -72733,7 +73632,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; @@ -72763,14 +73662,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -72826,8 +73727,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -72917,10 +73818,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -72948,9 +73850,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384 /* TypeParameter */) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -72958,16 +73861,20 @@ var ts; if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -73028,11 +73935,11 @@ var ts; // JsDoc tag includes both "@" and tag-name var requestJsDocTag = false; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); // Completion not allowed inside comments, bail out if this is the case - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -73083,7 +73990,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -73112,7 +74019,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -73171,6 +74078,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -73204,7 +74112,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; @@ -73255,6 +74163,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -73264,6 +74173,11 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { @@ -73437,16 +74351,16 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { @@ -73469,7 +74383,11 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -73480,10 +74398,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -73525,6 +74439,53 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32 /* Static */) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -73561,6 +74522,44 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17 /* OpenBraceToken */: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number; | } + case 26 /* CommaToken */: + case 25 /* SemicolonToken */: + // class c { method() { } | } + case 18 /* CloseBraceToken */: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + // class c { method() { } | method2() { } } + if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -73673,7 +74672,7 @@ var ts; containingNodeKind === 231 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; + return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 146 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && @@ -73686,13 +74685,17 @@ var ts; return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || containingNodeKind === 240 /* NamespaceImport */; + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: case 89 /* FunctionKeyword */: case 104 /* VarKeyword */: - case 125 /* GetKeyword */: - case 135 /* SetKeyword */: case 91 /* ImportKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: @@ -73700,6 +74703,12 @@ var ts; case 138 /* TypeKeyword */: return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -73742,7 +74751,7 @@ var ts; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -73776,7 +74785,7 @@ var ts; continue; } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -73790,12 +74799,55 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 149 /* PropertyDeclaration */ && + m.kind !== 151 /* MethodDeclaration */ && + m.kind !== 153 /* GetAccessor */ && + m.kind !== 154 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + var mIsStatic = ts.hasModifier(m, 32 /* Static */); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8 /* Private */); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24 /* NonPublicAccessibilityModifier */); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * @@ -73807,7 +74859,7 @@ var ts; for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253 /* JsxAttribute */) { @@ -73816,6 +74868,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } /** * Get the name to be display in completion from a given symbol. @@ -73868,6 +74923,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 123 /* ConstructorKeyword */: + case 131 /* ReadonlyKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 120 /* AsyncKeyword */: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -73884,9 +74960,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -73898,8 +74974,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -74693,6 +75769,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74771,11 +75850,42 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -74799,7 +75909,7 @@ var ts; } /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -74827,26 +75937,20 @@ var ts; } } }); - if (sourceFile.flags & 65536 /* JavaScriptFile */) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 /* ImportDeclaration */ || decl.kind === 244 /* ExportDeclaration */) { - return decl; + switch (decl.kind) { + case 181 /* CallExpression */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return decl; + case 248 /* ExternalModuleReference */: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248 /* ExternalModuleReference */); - return decl.parent; } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. @@ -74983,12 +76087,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); - ts.Debug.assert(!!name); - return name; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { @@ -75035,12 +76140,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. @@ -75051,44 +76157,50 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + // A node in a JSDoc comment can't have an implementation anyway. + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265 /* SourceFile */) { + return undefined; + } + var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -75098,10 +76210,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -75242,7 +76350,7 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265 /* SourceFile */) { return undefined; @@ -75253,6 +76361,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -75263,13 +76372,60 @@ var ts; // Can't have references to something that we have no symbol for. return undefined; } - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9 /* StringLiteral */) { + return false; + } + switch (node.parent.kind) { + case 233 /* ModuleDeclaration */: + case 248 /* ExternalModuleReference */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return true; + case 181 /* CallExpression */: + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265 /* 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 233 /* ModuleDeclaration */: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { @@ -75510,7 +76666,11 @@ var ts; // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. @@ -75542,16 +76702,12 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -75561,31 +76717,31 @@ var ts; // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case 71 /* Identifier */: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + // Want fullStart so we can find the symbol in JSDoc comments + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, /*fullStart*/ true); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -75604,15 +76760,13 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments || container.jsDoc !== undefined); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { // This wasn't the start of a token. Check to see if it might be a // match in a comment or string if that's what the caller is asking @@ -75738,7 +76892,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76004,10 +77158,10 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; - var node = ts.getTouchingWord(sourceFile, position); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; } @@ -76058,13 +77212,13 @@ var ts; if (searchSpaceNode.kind === 265 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -76073,7 +77227,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || !ts.isThis(node)) { return; } @@ -76110,10 +77264,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -76121,9 +77275,9 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; + var node_7 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); } @@ -76319,20 +77473,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -76476,7 +77630,7 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -76501,17 +77655,10 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 71 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 242 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 241 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -76530,16 +77677,6 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -76550,23 +77687,17 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -76579,13 +77710,13 @@ var ts; return undefined; } if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -76593,6 +77724,28 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239 /* ImportClause */: + case 237 /* ImportEqualsDeclaration */: + return true; + case 242 /* ImportSpecifier */: + return declaration.parent.kind === 241 /* NamedImports */; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -76663,7 +77816,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -76691,7 +77844,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -76763,6 +77916,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -76773,8 +77927,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -76894,7 +78046,7 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -77257,8 +78409,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. @@ -77301,17 +78453,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77340,8 +78495,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77379,6 +78535,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77388,8 +78545,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77641,8 +78798,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77731,9 +78888,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77750,7 +78907,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -79128,138 +80285,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -81588,9 +82640,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -81601,18 +82653,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -81620,51 +82668,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, + 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81689,6 +82766,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -81704,123 +82783,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true - // so if the option is undefined, we should treat it as true as well - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -82074,7 +83039,7 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -82171,7 +83136,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -83069,9 +84034,7 @@ var ts; if (node.kind === 20 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -83385,7 +84348,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { // find first non-whitespace position in the leading trivia of the node var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -83397,7 +84360,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -83474,7 +84437,7 @@ var ts; if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -83665,7 +84628,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); @@ -83694,27 +84657,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited @@ -83759,6 +84703,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -83827,14 +84781,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -83858,6 +84812,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -83868,7 +84867,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -83924,7 +84923,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -83933,7 +84933,7 @@ var ts; // This is the identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } @@ -84014,7 +85014,7 @@ var ts; /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); - var indexSignature = ts.createIndexSignatureDeclaration( + var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -84031,6 +85031,60 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 793064 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 107455 /* Value */; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84047,7 +85101,7 @@ var ts; var start = context.span.start; // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -84085,7 +85139,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 99 /* ThisKeyword */) { return undefined; } @@ -84133,7 +85187,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 123 /* ConstructorKeyword */) { return undefined; } @@ -84158,7 +85212,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { return undefined; @@ -84198,7 +85252,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } @@ -84225,138 +85279,142 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); // this handles var ["computed"] = 12; if (token.kind === 21 /* OpenBracketToken */) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); } switch (token.kind) { case 71 /* Identifier */: - switch (token.parent.kind) { - case 226 /* VariableDeclaration */: - switch (token.parent.parent.parent.kind) { - case 214 /* ForStatement */: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216 /* ForOfStatement */: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return undefined; - case 260 /* CatchClause */: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - // TODO: #14885 - // falls through - case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); - case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); - } - else { - // delete import specifier - return deleteNodeInList(token.parent); - } - // handle case where "import d, * as ns from './file'" - // or "'import {a, b as ns} from './file'" - case 239 /* ImportClause */: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - // import |d,| * as ns from './file' - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226 /* VariableDeclaration */: + return deleteVariableDeclaration(token.parent); + case 145 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + // handle case where 'import a = A;' + case 237 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); + return deleteNode(importEquals); + case 242 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); + return deleteNode(importSpec); + } + else { + // delete import specifier + return deleteNodeInList(token.parent); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 239 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + // import |d,| * as ns from './file' + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + // token.parent is a variableDeclaration + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214 /* ForStatement */: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -84388,6 +85446,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -84485,400 +85552,393 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238 /* ImportDeclaration */) { + return node; } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + // insert after any existing imports + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + : isNamespaceImport + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - // if node_modules folder is in this folder or any of its parent folder, no need to keep it. - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -84905,7 +85965,7 @@ var ts; // We also want to check if the previous line holds a comment for a node on the next line // if so, we do not want to separate the node from its comment if we can. if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -85010,7 +86070,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85068,7 +86128,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -85124,7 +86184,7 @@ var ts; /*returnType*/ undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration( + return ts.createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } @@ -85147,6 +86207,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -85156,6 +86217,188 @@ var ts; /// /// /// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 /* Function */ && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186 /* FunctionExpression */: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + case 187 /* ArrowFunction */: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 207 /* Block */) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + default: + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -85182,11 +86425,15 @@ var ts; /// /// /// +/// /// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; + /* @internal */ + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : @@ -85237,6 +86484,7 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + ts.Debug.assert(token !== 1 /* EndOfFileToken */); // Else it would infinitely loop var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -85264,27 +86512,32 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143 /* FirstNode */) { + if (ts.isJSDocTag(this)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + } + else if (this.kind >= 143 /* FirstNode */) { + var children_4 = []; ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; var pos_3 = this.pos; var useJSDocScanner_1 = this.kind >= 283 /* FirstJSDocTagNode */ && this.kind <= 293 /* LastJSDocTagNode */; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, node.pos, useJSDocScanner_1); } - children.push(node); + children_4.push(node); if (!isJSDocTagNode) { pos_3 = node.end; } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, nodes.pos, useJSDocScanner_1); } - children.push(_this.createSyntaxList(nodes)); + children_4.push(_this.createSyntaxList(nodes)); pos_3 = nodes.end; }; // jsDocComments need to be the first children @@ -85300,11 +86553,14 @@ var ts; pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); + this.addSyntheticNodes(children_4, pos_3, this.end); } ts.scanner.setText(undefined); + this._children = children_4; + } + else { + this._children = ts.emptyArray; } - this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -85571,13 +86827,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -85962,7 +87219,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -85987,10 +87244,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - // Ensure rules are initialized and up to date wrt to formatting options - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -86228,7 +87481,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -86283,7 +87536,7 @@ var ts; /// Goto implementation function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -86300,7 +87553,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -86333,11 +87586,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { @@ -86382,7 +87635,7 @@ var ts; function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { return; } @@ -86476,7 +87729,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); // Ensure that there is a corresponding token to match ours. @@ -86640,8 +87893,7 @@ var ts; var matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -86729,11 +87981,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -86859,20 +88135,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -86915,7 +88191,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line @@ -88130,6 +89406,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 01d5540db54..6a17eeffb8a 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -359,9 +359,10 @@ declare namespace ts { SyntaxList = 294, NotEmittedStatement = 295, PartiallyEmittedExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + CommaListExpression = 297, + MergeDeclarationMarker = 298, + EndOfDeclarationMarker = 299, + Count = 300, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -474,6 +475,10 @@ declare namespace ts { type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; + /** + * Text of identifier (with escapes converted to characters). + * If the identifier begins with two underscores, this will begin with three. + */ text: string; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; @@ -491,9 +496,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +511,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +519,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +532,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +544,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +553,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +575,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +597,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +605,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +957,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1016,7 +1023,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind; + keywordToken: SyntaxKind.NewKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1076,6 +1083,13 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ + interface CommaListExpression extends Expression { + kind: SyntaxKind.CommaListExpression; + elements: NodeArray; + } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1197,7 +1211,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1224,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1252,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1311,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1344,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1481,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -1706,11 +1720,11 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; + getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; @@ -1720,38 +1734,48 @@ declare namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + getContextualType(node: Expression): Type | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type; + getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; + getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; + getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; } enum NodeBuilderFlags { None = 0, - allowThisInObjectLiteral = 1, - allowQualifedNameInPlaceOfIdentifier = 2, - allowTypeParameterInQualifiedName = 4, - allowAnonymousIdentifier = 8, - allowEmptyUnionOrIntersection = 16, - allowEmptyTuple = 32, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + AllowThisInObjectLiteral = 1024, + AllowQualifedNameInPlaceOfIdentifier = 2048, + AllowAnonymousIdentifier = 8192, + AllowEmptyUnionOrIntersection = 16384, + AllowEmptyTuple = 32768, + IgnoreErrors = 60416, + InObjectTypeLiteral = 1048576, + InTypeAlias = 8388608, } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1912,18 +1936,18 @@ declare namespace ts { Index = 262144, IndexedAccess = 524288, NonPrimitive = 16777216, - Literal = 480, + Literal = 224, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, - NumberLike = 340, + NumberLike = 84, BooleanLike = 136, EnumLike = 272, UnionOrIntersection = 196608, StructuredType = 229376, StructuredOrTypeVariable = 1032192, TypeVariable = 540672, - Narrowable = 17810431, + Narrowable = 17810175, NotUnionOrUnit = 16810497, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -1935,15 +1959,17 @@ declare namespace ts { aliasTypeArguments?: Type[]; } interface LiteralType extends Type { - text: string; + value: string | number; freshType?: LiteralType; regularType?: LiteralType; } - interface EnumType extends Type { - memberTypes: EnumLiteralType[]; + interface StringLiteralType extends LiteralType { + value: string; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + interface NumberLiteralType extends LiteralType { + value: number; + } + interface EnumType extends Type { } enum ObjectFlags { Class = 1, @@ -1988,7 +2014,7 @@ declare namespace ts { */ interface TypeReference extends ObjectType { target: GenericType; - typeArguments: Type[]; + typeArguments?: Type[]; } interface GenericType extends InterfaceType, TypeReference { } @@ -2024,7 +2050,7 @@ declare namespace ts { } interface Signature { declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { @@ -2059,9 +2085,9 @@ declare namespace ts { next?: DiagnosticMessageChain; } interface Diagnostic { - file: SourceFile; - start: number; - length: number; + file: SourceFile | undefined; + start: number | undefined; + length: number | undefined; messageText: string | DiagnosticMessageChain; category: DiagnosticCategory; code: number; @@ -2329,6 +2355,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2611,14 +2638,14 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ - function getShebang(text: string): string; + function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; @@ -2695,6 +2722,7 @@ declare namespace ts { * @returns The unescaped identifier text. */ function unescapeIdentifier(identifier: string): string; + function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; } declare namespace ts { /** @@ -2709,6 +2737,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; + function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -2727,58 +2756,19 @@ declare namespace ts { function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; - function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; - function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; - function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; - function createThisTypeNode(): ThisTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; - function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; - function createTypeQueryNode(exprName: EntityName): TypeQueryNode; - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode; - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray): UnionOrIntersectionTypeNode; - function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; - function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; - function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; function createDecorator(expression: Expression): Decorator; function updateDecorator(node: Decorator, expression: Expression): Decorator; + function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration; - function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; @@ -2786,6 +2776,45 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; + function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; + function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; + function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; + function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; + function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode; + function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; + function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; + function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; + function createTypeQueryNode(exprName: EntityName): TypeQueryNode; + function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; + function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode; + function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; + function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; + function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode; + function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; + function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode; + function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; + function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + function createThisTypeNode(): ThisTypeNode; + function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; + function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; + function createLiteralTypeNode(literal: Expression): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern; @@ -2827,7 +2856,7 @@ declare namespace ts { function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; @@ -2847,16 +2876,15 @@ 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 createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + function createSemicolonClassElement(): SemicolonClassElement; function createBlock(statements: Statement[], multiLine?: boolean): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; - function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2888,10 +2916,19 @@ declare namespace ts { function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + function createDebuggerStatement(): DebuggerStatement; + function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; + function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration; function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration; function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; @@ -2900,6 +2937,8 @@ declare namespace ts { function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; @@ -2930,20 +2969,20 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; - function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes; function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; - function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCaseClause(expression: Expression, statements: Statement[]): CaseClause; function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; function createDefaultClause(statements: Statement[]): DefaultClause; function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; @@ -2976,6 +3015,8 @@ declare namespace ts { */ function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createCommaList(elements: Expression[]): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; function createComma(left: Expression, right: Expression): Expression; @@ -3040,11 +3081,11 @@ declare namespace ts { /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; /** * Sets the constant value to emit for an expression. */ - function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; /** * Adds an EmitHelper to a node. */ @@ -3069,17 +3110,13 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** Array that is only intended to be pushed to, never read. */ - interface Push { - push(value: T): void; - } function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; @@ -3218,6 +3255,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } @@ -3246,9 +3284,10 @@ declare namespace ts { * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3422,6 +3461,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; + getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3492,6 +3533,10 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + interface ApplicableRefactorInfo { + name: string; + description: string; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -4006,6 +4051,7 @@ declare namespace ts { reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: MapLike; + transformers?: CustomTransformers; } interface TranspileOutput { outputText: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 4fe0eb9bf25..a59610eae73 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -365,10 +365,11 @@ var ts; // Transformation nodes SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -512,6 +513,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + /* @internal */ + var StructureIsReused; + (function (StructureIsReused) { + StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; + StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; + StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; + })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); /** Return code used by getEmitOutput function to indicate status of the function */ var ExitStatus; (function (ExitStatus) { @@ -527,12 +535,23 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + // Options + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + // Error handling + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + // State + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { @@ -677,6 +696,12 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var EnumKind; + (function (EnumKind) { + EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) + })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -751,7 +776,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -761,7 +786,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; @@ -770,7 +795,7 @@ var ts; TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; @@ -1119,6 +1144,7 @@ var ts; EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; + EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1138,17 +1164,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1450,12 +1481,6 @@ var ts; return undefined; } ts.forEach = forEach; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1477,6 +1502,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1704,6 +1738,35 @@ var ts; return result; } ts.flatMap = flatMap; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * Avoids allocation if all elements map to themselves. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2881,6 +2944,11 @@ var ts; } ts.startsWith = startsWith; /* @internal */ + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -4058,6 +4126,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -4165,7 +4234,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -4360,6 +4429,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4655,6 +4732,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -4700,6 +4778,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4781,6 +4861,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -5443,9 +5526,10 @@ var ts; ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -6654,9 +6738,7 @@ var ts; ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - if (names.length !== newResolutions.length) { - return false; - } + ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; var oldResolution = oldResolutions && oldResolutions.get(names[i]); @@ -6849,28 +6931,30 @@ var ts; if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } + var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); + return '"' + escapeText(node.text) + '"'; case 13 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); + return "`" + escapeText(node.text) + "`"; case 14 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return "`" + escapeText(node.text) + "${"; case 15 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return "}" + escapeText(node.text) + "${"; case 16 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); + return "}" + escapeText(node.text) + "`"; case 8 /* NumericLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } + ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -7099,10 +7183,6 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isDeclarationFile(file) { - return file.isDeclarationFile; - } - ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { return node.kind === 232 /* EnumDeclaration */ && isConst(node); } @@ -7382,6 +7462,15 @@ var ts; return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 151 /* MethodDeclaration */: @@ -7638,6 +7727,10 @@ var ts; } } ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; function getInvokedExpression(node) { if (node.kind === 183 /* TaggedTemplateExpression */) { return node.tag; @@ -8074,9 +8167,6 @@ var ts; } ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } var func = param.parent; var tags = getJSDocTags(func, 286 /* JSDocParameterTag */); if (!param.name) { @@ -8098,6 +8188,19 @@ var ts; } } ts.getJSDocParameterTags = getJSDocParameterTags; + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterFromJSDoc(node) { + var name = node.parameterName.text; + var grandParent = node.parent.parent; + ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */); + if (!isFunctionLike(grandParent)) { + return undefined; + } + return ts.find(grandParent.parameters, function (p) { + return p.name.kind === 71 /* Identifier */ && p.name.text === name; + }); + } + ts.getParameterFromJSDoc = getParameterFromJSDoc; function getJSDocType(node) { var tag = getFirstJSDocTag(node, 288 /* JSDocTypeTag */); if (!tag && node.kind === 146 /* Parameter */) { @@ -8230,19 +8333,14 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 71 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { - return false; + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return isDeclaration(name.parent) && name.parent.name === name; + default: + return false; } - var parent = name.parent; - if (parent.kind === 242 /* ImportSpecifier */ || parent.kind === 246 /* ExportSpecifier */) { - if (parent.propertyName) { - return true; - } - } - if (isDeclaration(parent)) { - return parent.name === name; - } - return false; } ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { @@ -8357,21 +8455,19 @@ var ts; var isNoDefaultLibRegEx = /^(\/\/\/\s*/gim; if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { - return { - isNoDefaultLib: true - }; + return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - if (refMatchResult || refLibResult) { - var start = commentRange.pos; - var end = commentRange.end; + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; return { fileReference: { - pos: start, - end: end, - fileName: (refMatchResult || refLibResult)[3] + pos: pos, + end: pos + match[3].length, + fileName: match[3] }, isNoDefaultLib: false, isTypeReferenceDirective: !!refLibResult @@ -8399,12 +8495,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8457,7 +8554,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -8740,6 +8838,8 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; + case 297 /* CommaListExpression */: + return 0; default: return -1; } @@ -8853,14 +8953,15 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiCharacters(s) { + function escapeNonAsciiString(s) { + s = escapeString(s); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; } - ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + ts.escapeNonAsciiString = escapeNonAsciiString; var indentStrings = ["", " "]; function getIndentString(level) { if (indentStrings[level] === undefined) { @@ -8949,7 +9050,7 @@ var ts; ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { + if (!file || file.isDeclarationFile) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -9015,7 +9116,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; /** @@ -9579,13 +9680,13 @@ var ts; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { - if (options.newLine === 0 /* CarriageReturnLineFeed */) { - return carriageReturnLineFeed; + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + return lineFeed; } - else if (options.newLine === 1 /* LineFeed */) { - return lineFeed; - } - else if (ts.sys) { + if (ts.sys) { return ts.sys.newLine; } return carriageReturnLineFeed; @@ -9913,10 +10014,6 @@ var ts; return node.kind === 71 /* Identifier */; } ts.isIdentifier = isIdentifier; - function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; - } - ts.isVoidExpression = isVoidExpression; function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; @@ -9989,9 +10086,20 @@ var ts; || kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */ || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */; + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; } ts.isClassElement = isClassElement; + function isTypeElement(node) { + var kind = node.kind; + return kind === 156 /* ConstructSignature */ + || kind === 155 /* CallSignature */ + || kind === 148 /* PropertySignature */ + || kind === 150 /* MethodSignature */ + || kind === 157 /* IndexSignature */ + || kind === 247 /* MissingDeclaration */; + } + ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; return kind === 261 /* PropertyAssignment */ @@ -10209,6 +10317,7 @@ var ts; || kind === 198 /* SpreadElement */ || kind === 202 /* AsExpression */ || kind === 200 /* OmittedExpression */ + || kind === 297 /* CommaListExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -10297,6 +10406,10 @@ var ts; return node.kind === 237 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238 /* ImportDeclaration */; + } + ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { return node.kind === 239 /* ImportClause */; } @@ -10319,6 +10432,10 @@ var ts; return node.kind === 246 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; function isModuleOrEnumDeclaration(node) { return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; } @@ -10390,8 +10507,8 @@ var ts; || kind === 213 /* WhileStatement */ || kind === 220 /* WithStatement */ || kind === 295 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + || kind === 299 /* EndOfDeclarationMarker */ + || kind === 298 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -10517,6 +10634,49 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } + ts.getCheckFlags = getCheckFlags; + function getDeclarationModifierFlagsFromSymbol(s) { + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; + } + ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; + function levenshtein(s1, s2) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + for (var i = 0; i < s2.length + 1; i++) { + previous[i] = i; + current[i] = -1; + } + for (var i = 1; i < s1.length + 1; i++) { + current[0] = i; + for (var j = 1; j < s2.length + 1; j++) { + current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); + } + // shift current back to previous, and then reuse previous' array + var tmp = previous; + previous = current; + current = tmp; + } + return previous[previous.length - 1]; + } + ts.levenshtein = levenshtein; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10891,6 +11051,27 @@ var ts; return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; })(ts || (ts = {})); /// /// @@ -10983,16 +11164,24 @@ var ts; node.textSourceNode = sourceNode; return node; } - // Identifiers - function createIdentifier(text) { + function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } return node; } ts.createIdentifier = createIdentifier; + function updateIdentifier(node, typeArguments) { + return node.typeArguments !== typeArguments + ? updateNode(createIdentifier(node.text, typeArguments), node) + : node; + } + ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable) { @@ -11087,240 +11276,13 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; - // Type Elements - function createSignatureDeclaration(kind, typeParameters, parameters, type) { - var signatureDeclaration = createSynthesizedNode(kind); - signatureDeclaration.typeParameters = asNodeArray(typeParameters); - signatureDeclaration.parameters = asNodeArray(parameters); - signatureDeclaration.type = type; - return signatureDeclaration; - } - ts.createSignatureDeclaration = createSignatureDeclaration; - function updateSignatureDeclaration(node, typeParameters, parameters, type) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) - : node; - } - function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); - } - ts.createFunctionTypeNode = createFunctionTypeNode; - function updateFunctionTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateFunctionTypeNode = updateFunctionTypeNode; - function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); - } - ts.createConstructorTypeNode = createConstructorTypeNode; - function updateConstructorTypeNode(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructorTypeNode = updateConstructorTypeNode; - function createCallSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); - } - ts.createCallSignatureDeclaration = createCallSignatureDeclaration; - function updateCallSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration; - function createConstructSignatureDeclaration(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); - } - ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration; - function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); - } - ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration; - function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var methodSignature = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); - methodSignature.name = asName(name); - methodSignature.questionToken = questionToken; - return methodSignature; - } - ts.createMethodSignature = createMethodSignature; - function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.name !== name - || node.questionToken !== questionToken - ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) - : node; - } - ts.updateMethodSignature = updateMethodSignature; - // Types - function createKeywordTypeNode(kind) { - return createSynthesizedNode(kind); - } - ts.createKeywordTypeNode = createKeywordTypeNode; - function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); - } - ts.createThisTypeNode = createThisTypeNode; - function createLiteralTypeNode(literal) { - var literalTypeNode = createSynthesizedNode(173 /* LiteralType */); - literalTypeNode.literal = literal; - return literalTypeNode; - } - ts.createLiteralTypeNode = createLiteralTypeNode; - function updateLiteralTypeNode(node, literal) { - return node.literal !== literal - ? updateNode(createLiteralTypeNode(literal), node) - : node; - } - ts.updateLiteralTypeNode = updateLiteralTypeNode; - function createTypeReferenceNode(typeName, typeArguments) { - var typeReference = createSynthesizedNode(159 /* TypeReference */); - typeReference.typeName = asName(typeName); - typeReference.typeArguments = asNodeArray(typeArguments); - return typeReference; - } - ts.createTypeReferenceNode = createTypeReferenceNode; - function updateTypeReferenceNode(node, typeName, typeArguments) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments - ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) - : node; - } - ts.updateTypeReferenceNode = updateTypeReferenceNode; - function createTypePredicateNode(parameterName, type) { - var typePredicateNode = createSynthesizedNode(158 /* TypePredicate */); - typePredicateNode.parameterName = asName(parameterName); - typePredicateNode.type = type; - return typePredicateNode; - } - ts.createTypePredicateNode = createTypePredicateNode; - function updateTypePredicateNode(node, parameterName, type) { - return node.parameterName !== parameterName - || node.type !== type - ? updateNode(createTypePredicateNode(parameterName, type), node) - : node; - } - ts.updateTypePredicateNode = updateTypePredicateNode; - function createTypeQueryNode(exprName) { - var typeQueryNode = createSynthesizedNode(162 /* TypeQuery */); - typeQueryNode.exprName = exprName; - return typeQueryNode; - } - ts.createTypeQueryNode = createTypeQueryNode; - function updateTypeQueryNode(node, exprName) { - return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node; - } - ts.updateTypeQueryNode = updateTypeQueryNode; - function createArrayTypeNode(elementType) { - var arrayTypeNode = createSynthesizedNode(164 /* ArrayType */); - arrayTypeNode.elementType = elementType; - return arrayTypeNode; - } - ts.createArrayTypeNode = createArrayTypeNode; - function updateArrayTypeNode(node, elementType) { - return node.elementType !== elementType - ? updateNode(createArrayTypeNode(elementType), node) - : node; - } - ts.updateArrayTypeNode = updateArrayTypeNode; - function createUnionOrIntersectionTypeNode(kind, types) { - var unionTypeNode = createSynthesizedNode(kind); - unionTypeNode.types = createNodeArray(types); - return unionTypeNode; - } - ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; - function updateUnionOrIntersectionTypeNode(node, types) { - return node.types !== types - ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) - : node; - } - ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode; - function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); - node.type = type; - return node; - } - ts.createParenthesizedType = createParenthesizedType; - function updateParenthesizedType(node, type) { - return node.type !== type - ? updateNode(createParenthesizedType(type), node) - : node; - } - ts.updateParenthesizedType = updateParenthesizedType; - function createTypeLiteralNode(members) { - var typeLiteralNode = createSynthesizedNode(163 /* TypeLiteral */); - typeLiteralNode.members = createNodeArray(members); - return typeLiteralNode; - } - ts.createTypeLiteralNode = createTypeLiteralNode; - function updateTypeLiteralNode(node, members) { - return node.members !== members - ? updateNode(createTypeLiteralNode(members), node) - : node; - } - ts.updateTypeLiteralNode = updateTypeLiteralNode; - function createTupleTypeNode(elementTypes) { - var tupleTypeNode = createSynthesizedNode(165 /* TupleType */); - tupleTypeNode.elementTypes = createNodeArray(elementTypes); - return tupleTypeNode; - } - ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { - return node.elementTypes !== elementTypes - ? updateNode(createTupleTypeNode(elementTypes), node) - : node; - } - ts.updateTypleTypeNode = updateTypleTypeNode; - function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var mappedTypeNode = createSynthesizedNode(172 /* MappedType */); - mappedTypeNode.readonlyToken = readonlyToken; - mappedTypeNode.typeParameter = typeParameter; - mappedTypeNode.questionToken = questionToken; - mappedTypeNode.type = type; - return mappedTypeNode; - } - ts.createMappedTypeNode = createMappedTypeNode; - function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.questionToken !== questionToken - || node.type !== type - ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) - : node; - } - ts.updateMappedTypeNode = updateMappedTypeNode; - function createTypeOperatorNode(type) { - var typeOperatorNode = createSynthesizedNode(170 /* TypeOperator */); - typeOperatorNode.operator = 127 /* KeyOfKeyword */; - typeOperatorNode.type = type; - return typeOperatorNode; - } - ts.createTypeOperatorNode = createTypeOperatorNode; - function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; - } - ts.updateTypeOperatorNode = updateTypeOperatorNode; - function createIndexedAccessTypeNode(objectType, indexType) { - var indexedAccessTypeNode = createSynthesizedNode(171 /* IndexedAccessType */); - indexedAccessTypeNode.objectType = objectType; - indexedAccessTypeNode.indexType = indexType; - return indexedAccessTypeNode; - } - ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; - function updateIndexedAccessTypeNode(node, objectType, indexType) { - return node.objectType !== objectType - || node.indexType !== indexType - ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) - : node; - } - ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; - // Type Declarations + // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var typeParameter = createSynthesizedNode(145 /* TypeParameter */); - typeParameter.name = asName(name); - typeParameter.constraint = constraint; - typeParameter.default = defaultType; - return typeParameter; + var node = createSynthesizedNode(145 /* TypeParameter */); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + return node; } ts.createTypeParameterDeclaration = createTypeParameterDeclaration; function updateTypeParameterDeclaration(node, name, constraint, defaultType) { @@ -11331,44 +11293,6 @@ var ts; : node; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; - // Signature elements - function createPropertySignature(name, questionToken, type, initializer) { - var propertySignature = createSynthesizedNode(148 /* PropertySignature */); - propertySignature.name = asName(name); - propertySignature.questionToken = questionToken; - propertySignature.type = type; - propertySignature.initializer = initializer; - return propertySignature; - } - ts.createPropertySignature = createPropertySignature; - function updatePropertySignature(node, name, questionToken, type, initializer) { - return node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? updateNode(createPropertySignature(name, questionToken, type, initializer), node) - : node; - } - ts.updatePropertySignature = updatePropertySignature; - function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) { - var indexSignature = createSynthesizedNode(157 /* IndexSignature */); - indexSignature.decorators = asNodeArray(decorators); - indexSignature.modifiers = asNodeArray(modifiers); - indexSignature.parameters = createNodeArray(parameters); - indexSignature.type = type; - return indexSignature; - } - ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration; - function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) { - return node.parameters !== parameters - || node.type !== type - || node.decorators !== decorators - || node.modifiers !== modifiers - ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node) - : node; - } - ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration; - // Signature elements function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { var node = createSynthesizedNode(146 /* Parameter */); node.decorators = asNodeArray(decorators); @@ -11405,7 +11329,27 @@ var ts; : node; } ts.updateDecorator = updateDecorator; - // Type members + // Type Elements + function createPropertySignature(modifiers, name, questionToken, type, initializer) { + var node = createSynthesizedNode(148 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createPropertySignature = createPropertySignature; + function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) { + return node.modifiers !== modifiers + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer + ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node) + : node; + } + ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { var node = createSynthesizedNode(149 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); @@ -11427,7 +11371,24 @@ var ts; : node; } ts.updateProperty = updateProperty; - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + function createMethodSignature(typeParameters, parameters, type, name, questionToken) { + var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + node.name = asName(name); + node.questionToken = questionToken; + return node; + } + ts.createMethodSignature = createMethodSignature; + function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node) + : node; + } + ts.updateMethodSignature = updateMethodSignature; + function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { var node = createSynthesizedNode(151 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -11440,7 +11401,7 @@ var ts; node.body = body; return node; } - ts.createMethodDeclaration = createMethodDeclaration; + ts.createMethod = createMethod; function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -11450,7 +11411,7 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } ts.updateMethod = updateMethod; @@ -11518,6 +11479,251 @@ var ts; : node; } ts.updateSetAccessor = updateSetAccessor; + function createCallSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + } + ts.createCallSignature = createCallSignature; + function updateCallSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateCallSignature = updateCallSignature; + function createConstructSignature(typeParameters, parameters, type) { + return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + } + ts.createConstructSignature = createConstructSignature; + function updateConstructSignature(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructSignature = updateConstructSignature; + function createIndexSignature(decorators, modifiers, parameters, type) { + var node = createSynthesizedNode(157 /* IndexSignature */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.type = type; + return node; + } + ts.createIndexSignature = createIndexSignature; + function updateIndexSignature(node, decorators, modifiers, parameters, type) { + return node.parameters !== parameters + || node.type !== type + || node.decorators !== decorators + || node.modifiers !== modifiers + ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node) + : node; + } + ts.updateIndexSignature = updateIndexSignature; + /* @internal */ + function createSignatureDeclaration(kind, typeParameters, parameters, type) { + var node = createSynthesizedNode(kind); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + return node; + } + ts.createSignatureDeclaration = createSignatureDeclaration; + function updateSignatureDeclaration(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) + : node; + } + // Types + function createKeywordTypeNode(kind) { + return createSynthesizedNode(kind); + } + ts.createKeywordTypeNode = createKeywordTypeNode; + function createTypePredicateNode(parameterName, type) { + var node = createSynthesizedNode(158 /* TypePredicate */); + node.parameterName = asName(parameterName); + node.type = type; + return node; + } + ts.createTypePredicateNode = createTypePredicateNode; + function updateTypePredicateNode(node, parameterName, type) { + return node.parameterName !== parameterName + || node.type !== type + ? updateNode(createTypePredicateNode(parameterName, type), node) + : node; + } + ts.updateTypePredicateNode = updateTypePredicateNode; + function createTypeReferenceNode(typeName, typeArguments) { + var node = createSynthesizedNode(159 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); + return node; + } + ts.createTypeReferenceNode = createTypeReferenceNode; + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName + || node.typeArguments !== typeArguments + ? updateNode(createTypeReferenceNode(typeName, typeArguments), node) + : node; + } + ts.updateTypeReferenceNode = updateTypeReferenceNode; + function createFunctionTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + } + ts.createFunctionTypeNode = createFunctionTypeNode; + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateFunctionTypeNode = updateFunctionTypeNode; + function createConstructorTypeNode(typeParameters, parameters, type) { + return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + } + ts.createConstructorTypeNode = createConstructorTypeNode; + function updateConstructorTypeNode(node, typeParameters, parameters, type) { + return updateSignatureDeclaration(node, typeParameters, parameters, type); + } + ts.updateConstructorTypeNode = updateConstructorTypeNode; + function createTypeQueryNode(exprName) { + var node = createSynthesizedNode(162 /* TypeQuery */); + node.exprName = exprName; + return node; + } + ts.createTypeQueryNode = createTypeQueryNode; + function updateTypeQueryNode(node, exprName) { + return node.exprName !== exprName + ? updateNode(createTypeQueryNode(exprName), node) + : node; + } + ts.updateTypeQueryNode = updateTypeQueryNode; + function createTypeLiteralNode(members) { + var node = createSynthesizedNode(163 /* TypeLiteral */); + node.members = createNodeArray(members); + return node; + } + ts.createTypeLiteralNode = createTypeLiteralNode; + function updateTypeLiteralNode(node, members) { + return node.members !== members + ? updateNode(createTypeLiteralNode(members), node) + : node; + } + ts.updateTypeLiteralNode = updateTypeLiteralNode; + function createArrayTypeNode(elementType) { + var node = createSynthesizedNode(164 /* ArrayType */); + node.elementType = ts.parenthesizeElementTypeMember(elementType); + return node; + } + ts.createArrayTypeNode = createArrayTypeNode; + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType + ? updateNode(createArrayTypeNode(elementType), node) + : node; + } + ts.updateArrayTypeNode = updateArrayTypeNode; + function createTupleTypeNode(elementTypes) { + var node = createSynthesizedNode(165 /* TupleType */); + node.elementTypes = createNodeArray(elementTypes); + return node; + } + ts.createTupleTypeNode = createTupleTypeNode; + function updateTypleTypeNode(node, elementTypes) { + return node.elementTypes !== elementTypes + ? updateNode(createTupleTypeNode(elementTypes), node) + : node; + } + ts.updateTypleTypeNode = updateTypleTypeNode; + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + } + ts.createUnionTypeNode = createUnionTypeNode; + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateUnionTypeNode = updateUnionTypeNode; + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + } + ts.createIntersectionTypeNode = createIntersectionTypeNode; + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types); + } + ts.updateIntersectionTypeNode = updateIntersectionTypeNode; + function createUnionOrIntersectionTypeNode(kind, types) { + var node = createSynthesizedNode(kind); + node.types = ts.parenthesizeElementTypeMembers(types); + return node; + } + ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode; + function updateUnionOrIntersectionTypeNode(node, types) { + return node.types !== types + ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node) + : node; + } + function createParenthesizedType(type) { + var node = createSynthesizedNode(168 /* ParenthesizedType */); + node.type = type; + return node; + } + ts.createParenthesizedType = createParenthesizedType; + function updateParenthesizedType(node, type) { + return node.type !== type + ? updateNode(createParenthesizedType(type), node) + : node; + } + ts.updateParenthesizedType = updateParenthesizedType; + function createThisTypeNode() { + return createSynthesizedNode(169 /* ThisType */); + } + ts.createThisTypeNode = createThisTypeNode; + function createTypeOperatorNode(type) { + var node = createSynthesizedNode(170 /* TypeOperator */); + node.operator = 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(type); + return node; + } + ts.createTypeOperatorNode = createTypeOperatorNode; + function updateTypeOperatorNode(node, type) { + return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + } + ts.updateTypeOperatorNode = updateTypeOperatorNode; + function createIndexedAccessTypeNode(objectType, indexType) { + var node = createSynthesizedNode(171 /* IndexedAccessType */); + node.objectType = ts.parenthesizeElementTypeMember(objectType); + node.indexType = indexType; + return node; + } + ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode; + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType + || node.indexType !== indexType + ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node) + : node; + } + ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; + function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { + var node = createSynthesizedNode(172 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.questionToken = questionToken; + node.type = type; + return node; + } + ts.createMappedTypeNode = createMappedTypeNode; + function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) { + return node.readonlyToken !== readonlyToken + || node.typeParameter !== typeParameter + || node.questionToken !== questionToken + || node.type !== type + ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node) + : node; + } + ts.updateMappedTypeNode = updateMappedTypeNode; + function createLiteralTypeNode(literal) { + var node = createSynthesizedNode(173 /* LiteralType */); + node.literal = literal; + return node; + } + ts.createLiteralTypeNode = createLiteralTypeNode; + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal + ? updateNode(createLiteralTypeNode(literal), node) + : node; + } + ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { var node = createSynthesizedNode(174 /* ObjectBindingPattern */); @@ -11565,9 +11771,8 @@ var ts; function createArrayLiteral(elements, multiLine) { var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createArrayLiteral = createArrayLiteral; @@ -11580,9 +11785,8 @@ var ts; function createObjectLiteral(properties, multiLine) { var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); - if (multiLine) { + if (multiLine) node.multiLine = true; - } return node; } ts.createObjectLiteral = createObjectLiteral; @@ -11632,9 +11836,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - return expression !== node.expression - || typeArguments !== node.typeArguments - || argumentsArray !== node.arguments + return node.expression !== expression + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? updateNode(createCall(expression, typeArguments, argumentsArray), node) : node; } @@ -11824,10 +12028,10 @@ var ts; return node; } ts.createBinary = createBinary; - function updateBinary(node, left, right) { + function updateBinary(node, left, right, operator) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, node.operatorToken, right), node) + ? updateNode(createBinary(left, operator || node.operatorToken, right), node) : node; } ts.updateBinary = updateBinary; @@ -11954,6 +12158,19 @@ var ts; : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createMetaProperty(keywordToken, name) { + var node = createSynthesizedNode(204 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + return node; + } + ts.createMetaProperty = createMetaProperty; + function updateMetaProperty(node, name) { + return node.name !== name + ? updateNode(createMetaProperty(node.keywordToken, name), node) + : node; + } + ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { var node = createSynthesizedNode(205 /* TemplateSpan */); @@ -11969,6 +12186,10 @@ var ts; : node; } ts.updateTemplateSpan = updateTemplateSpan; + function createSemicolonClassElement() { + return createSynthesizedNode(206 /* SemicolonClassElement */); + } + ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { var block = createSynthesizedNode(207 /* Block */); @@ -11979,7 +12200,7 @@ var ts; } ts.createBlock = createBlock; function updateBlock(node, statements) { - return statements !== node.statements + return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } @@ -11999,35 +12220,6 @@ var ts; : node; } ts.updateVariableStatement = updateVariableStatement; - function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); - node.flags |= flags; - node.declarations = createNodeArray(declarations); - return node; - } - ts.createVariableDeclarationList = createVariableDeclarationList; - function updateVariableDeclarationList(node, declarations) { - return node.declarations !== declarations - ? updateNode(createVariableDeclarationList(declarations, node.flags), node) - : node; - } - ts.updateVariableDeclarationList = updateVariableDeclarationList; - function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); - node.name = asName(name); - node.type = type; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; - return node; - } - ts.createVariableDeclaration = createVariableDeclaration; - function updateVariableDeclaration(node, name, type, initializer) { - return node.name !== name - || node.type !== type - || node.initializer !== initializer - ? updateNode(createVariableDeclaration(name, type, initializer), node) - : node; - } - ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement() { return createSynthesizedNode(209 /* EmptyStatement */); } @@ -12246,6 +12438,39 @@ var ts; : node; } ts.updateTry = updateTry; + function createDebuggerStatement() { + return createSynthesizedNode(225 /* DebuggerStatement */); + } + ts.createDebuggerStatement = createDebuggerStatement; + function createVariableDeclaration(name, type, initializer) { + var node = createSynthesizedNode(226 /* VariableDeclaration */); + node.name = asName(name); + node.type = type; + node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + return node.name !== name + || node.type !== type + || node.initializer !== initializer + ? updateNode(createVariableDeclaration(name, type, initializer), node) + : node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createVariableDeclarationList(declarations, flags) { + var node = createSynthesizedNode(227 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations + ? updateNode(createVariableDeclarationList(declarations, node.flags), node) + : node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { var node = createSynthesizedNode(228 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); @@ -12294,6 +12519,48 @@ var ts; : node; } ts.updateClassDeclaration = updateClassDeclaration; + function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { + var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createInterfaceDeclaration = createInterfaceDeclaration; + function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members + ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + : node; + } + ts.updateInterfaceDeclaration = updateInterfaceDeclaration; + function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { + var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + node.decorators = asNodeArray(decorators); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + return node; + } + ts.createTypeAliasDeclaration = createTypeAliasDeclaration; + function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { + return node.decorators !== decorators + || node.modifiers !== modifiers + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type + ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + : node; + } + ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { var node = createSynthesizedNode(232 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); @@ -12314,7 +12581,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { var node = createSynthesizedNode(233 /* ModuleDeclaration */); - node.flags |= flags; + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -12355,6 +12622,18 @@ var ts; : node; } ts.updateCaseBlock = updateCaseBlock; + function createNamespaceExportDeclaration(name) { + var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + node.name = asName(name); + return node; + } + ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration; + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name + ? updateNode(createNamespaceExportDeclaration(name), node) + : node; + } + ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); @@ -12385,7 +12664,8 @@ var ts; function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { return node.decorators !== decorators || node.modifiers !== modifiers - || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node) : node; } @@ -12573,19 +12853,6 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; - function createJsxAttributes(properties) { - var jsxAttributes = createSynthesizedNode(254 /* JsxAttributes */); - jsxAttributes.properties = createNodeArray(properties); - return jsxAttributes; - } - ts.createJsxAttributes = createJsxAttributes; - function updateJsxAttributes(jsxAttributes, properties) { - if (jsxAttributes.properties !== properties) { - return updateNode(createJsxAttributes(properties), jsxAttributes); - } - return jsxAttributes; - } - ts.updateJsxAttributes = updateJsxAttributes; function createJsxAttribute(name, initializer) { var node = createSynthesizedNode(253 /* JsxAttribute */); node.name = name; @@ -12600,6 +12867,18 @@ var ts; : node; } ts.updateJsxAttribute = updateJsxAttribute; + function createJsxAttributes(properties) { + var node = createSynthesizedNode(254 /* JsxAttributes */); + node.properties = createNodeArray(properties); + return node; + } + ts.createJsxAttributes = createJsxAttributes; + function updateJsxAttributes(node, properties) { + return node.properties !== properties + ? updateNode(createJsxAttributes(properties), node) + : node; + } + ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); node.expression = expression; @@ -12626,20 +12905,6 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; // Clauses - function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); - node.token = token; - node.types = createNodeArray(types); - return node; - } - ts.createHeritageClause = createHeritageClause; - function updateHeritageClause(node, types) { - if (node.types !== types) { - return updateNode(createHeritageClause(node.token, types), node); - } - return node; - } - ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements) { var node = createSynthesizedNode(257 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); @@ -12648,10 +12913,10 @@ var ts; } ts.createCaseClause = createCaseClause; function updateCaseClause(node, expression, statements) { - if (node.expression !== expression || node.statements !== statements) { - return updateNode(createCaseClause(expression, statements), node); - } - return node; + return node.expression !== expression + || node.statements !== statements + ? updateNode(createCaseClause(expression, statements), node) + : node; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { @@ -12661,12 +12926,24 @@ var ts; } ts.createDefaultClause = createDefaultClause; function updateDefaultClause(node, statements) { - if (node.statements !== statements) { - return updateNode(createDefaultClause(statements), node); - } - return node; + return node.statements !== statements + ? updateNode(createDefaultClause(statements), node) + : node; } ts.updateDefaultClause = updateDefaultClause; + function createHeritageClause(token, types) { + var node = createSynthesizedNode(259 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + return node.types !== types + ? updateNode(createHeritageClause(node.token, types), node) + : node; + } + ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { var node = createSynthesizedNode(260 /* CatchClause */); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; @@ -12675,10 +12952,10 @@ var ts; } ts.createCatchClause = createCatchClause; function updateCatchClause(node, variableDeclaration, block) { - if (node.variableDeclaration !== variableDeclaration || node.block !== block) { - return updateNode(createCatchClause(variableDeclaration, block), node); - } - return node; + return node.variableDeclaration !== variableDeclaration + || node.block !== block + ? updateNode(createCatchClause(variableDeclaration, block), node) + : node; } ts.updateCatchClause = updateCatchClause; // Property assignments @@ -12691,10 +12968,10 @@ var ts; } ts.createPropertyAssignment = createPropertyAssignment; function updatePropertyAssignment(node, name, initializer) { - if (node.name !== name || node.initializer !== initializer) { - return updateNode(createPropertyAssignment(name, initializer), node); - } - return node; + return node.name !== name + || node.initializer !== initializer + ? updateNode(createPropertyAssignment(name, initializer), node) + : node; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { @@ -12705,10 +12982,10 @@ var ts; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { - if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { - return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node); - } - return node; + return node.name !== name + || node.objectAssignmentInitializer !== objectAssignmentInitializer + ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + : node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { @@ -12718,10 +12995,9 @@ var ts; } ts.createSpreadAssignment = createSpreadAssignment; function updateSpreadAssignment(node, expression) { - if (node.expression !== expression) { - return updateNode(createSpreadAssignment(expression), node); - } - return node; + return node.expression !== expression + ? updateNode(createSpreadAssignment(expression), node) + : node; } ts.updateSpreadAssignment = updateSpreadAssignment; // Enum @@ -12833,7 +13109,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12845,7 +13121,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -12874,6 +13150,29 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function flattenCommaElements(node) { + if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (node.kind === 297 /* CommaListExpression */) { + return node.elements; + } + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaList(elements) { + var node = createSynthesizedNode(297 /* CommaListExpression */); + node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); + return node; + } + ts.createCommaList = createCommaList; + function updateCommaList(node, elements) { + return node.elements !== elements + ? updateNode(createCommaList(elements), node) + : node; + } + ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { var node = ts.createNode(266 /* Bundle */); node.sourceFiles = sourceFiles; @@ -13250,7 +13549,25 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // Compound nodes + ts.nullTransformationContext = { + enableEmitNotification: ts.noop, + enableSubstitution: ts.noop, + endLexicalEnvironment: function () { return undefined; }, + getCompilerOptions: ts.notImplemented, + getEmitHost: ts.notImplemented, + getEmitResolver: ts.notImplemented, + hoistFunctionDeclaration: ts.noop, + hoistVariableDeclaration: ts.noop, + isEmitNotificationEnabled: ts.notImplemented, + isSubstitutionEnabled: ts.notImplemented, + onEmitNode: ts.noop, + onSubstituteNode: ts.notImplemented, + readEmitHelpers: ts.notImplemented, + requestEmitHelper: ts.noop, + resumeLexicalEnvironment: ts.noop, + startLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop + }; function createTypeCheck(value, tag) { return tag === "undefined" ? ts.createStrictEquality(value, ts.createVoidZero()) @@ -13512,7 +13829,11 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { - return ts.reduceLeft(expressions, ts.createComma); + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. + return expressions.length > 10 + ? ts.createCommaList(expressions) + : ts.reduceLeft(expressions, ts.createComma); } ts.inlineExpressions = inlineExpressions; function createExpressionFromEntityName(node) { @@ -13686,9 +14007,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13846,16 +14168,6 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; - function parenthesizeConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); - var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { - return ts.createParen(condition); - } - return condition; - } - ts.parenthesizeConditionalHead = parenthesizeConditionalHead; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -14131,6 +14443,34 @@ var ts; return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function parenthesizeElementTypeMember(member) { + switch (member.kind) { + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return ts.createParenthesizedType(member); + } + return member; + } + ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeElementTypeMembers(members) { + return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); + } + ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; + function parenthesizeTypeParameters(typeParameters) { + if (ts.some(typeParameters)) { + var nodeArray = ts.createNodeArray(); + for (var i = 0; i < typeParameters.length; ++i) { + var entry = typeParameters[i]; + nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + ts.createParenthesizedType(entry) : + entry); + } + return nodeArray; + } + } + ts.parenthesizeTypeParameters = parenthesizeTypeParameters; /** * Clones a series of not-emitted expressions with a new inner expression. * @@ -14311,7 +14651,7 @@ var ts; if (file.moduleName) { return ts.createLiteral(file.moduleName); } - if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + if (!file.isDeclarationFile && (options.out || options.outFile)) { return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); } return undefined; @@ -15079,6 +15419,8 @@ var ts; return visitNode(cbNode, node.expression); case 247 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 297 /* CommaListExpression */: + return visitNodes(cbNodes, node.elements); case 249 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || @@ -20465,6 +20807,8 @@ var ts; case "augments": tag = parseAugmentsTag(atToken, tagName); break; + case "arg": + case "argument": case "param": tag = parseParamTag(atToken, tagName); break; @@ -21452,7 +21796,7 @@ var ts; inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; - skipTransformFlagAggregation = ts.isDeclarationFile(file); + skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -21480,7 +21824,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -21517,12 +21861,13 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21530,7 +21875,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21548,18 +21893,9 @@ var ts; case 243 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; case 194 /* BinaryExpression */: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2 /* ModuleExports */: - // module.exports = ... - return "export="; - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - // exports.x = ... or this.y = ... - return node.left.name.text; - case 3 /* PrototypeProperty */: - // className.prototype.methodName = ... - return node.left.expression.name.text; + if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; @@ -21674,9 +22010,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -21711,6 +22047,8 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (node.kind === 290 /* JSDocTypedefTag */) + ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. var isJSDocTypedefInJSDocNamespace = node.kind === 290 /* JSDocTypedefTag */ && node.name && node.name.kind === 71 /* Identifier */ && @@ -21869,9 +22207,7 @@ var ts; // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } + ts.forEach(node.jsDoc, bind); if (checkUnreachable(node)) { bindEachChild(node); return; @@ -23057,9 +23393,7 @@ var ts; // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } + bindJSDocTypedefTagIfAny(node); // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible // destination symbol tables are: @@ -23141,7 +23475,7 @@ var ts; // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. - if (node.isInJSDocNamespace) { + if (ts.isInJavaScriptFile(node) && node.isInJSDocNamespace) { var parentNode = node.parent; while (parentNode && parentNode.kind !== 290 /* JSDocTypedefTag */) { parentNode = parentNode.parent; @@ -23211,10 +23545,7 @@ var ts; return bindVariableDeclarationOrBindingElement(node); case 149 /* PropertyDeclaration */: case 148 /* PropertySignature */: - case 276 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - case 291 /* JSDocPropertyTag */: - return bindJSDocProperty(node); + return bindPropertyWorker(node); case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); @@ -23256,13 +23587,10 @@ var ts; return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); case 160 /* FunctionType */: case 161 /* ConstructorType */: - case 279 /* JSDocFunctionType */: return bindFunctionOrConstructorType(node); case 163 /* TypeLiteral */: case 172 /* MappedType */: - case 292 /* JSDocTypeLiteral */: - case 275 /* JSDocRecordType */: - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + return bindAnonymousTypeWorker(node); case 178 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 186 /* FunctionExpression */: @@ -23281,11 +23609,6 @@ var ts; return bindClassLikeDeclaration(node); case 230 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 290 /* JSDocTypedefTag */: - if (!node.fullName || node.fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - } - break; case 231 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); case 232 /* EnumDeclaration */: @@ -23321,8 +23644,37 @@ var ts; // falls through case 234 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); + default: + if (ts.isInJavaScriptFile(node)) + return bindJSDocWorker(node); } } + function bindJSDocWorker(node) { + switch (node.kind) { + case 276 /* JSDocRecordMember */: + return bindPropertyWorker(node); + case 291 /* JSDocPropertyTag */: + return declareSymbolAndAddToSymbolTable(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 279 /* JSDocFunctionType */: + return bindFunctionOrConstructorType(node); + case 292 /* JSDocTypeLiteral */: + case 275 /* JSDocRecordType */: + return bindAnonymousTypeWorker(node); + case 290 /* JSDocTypedefTag */: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71 /* Identifier */) { + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; if (parameterName && parameterName.kind === 71 /* Identifier */) { @@ -23592,7 +23944,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode) { + if (inStrictMode && !ts.isInAmbientContext(node)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -23611,7 +23963,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23626,7 +23978,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -23639,10 +23991,8 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { node.flowNode = currentFlow; @@ -23651,9 +24001,6 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4 /* Property */, 0 /* PropertyExcludes */); - } // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); @@ -24526,13 +24873,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -24860,6 +25205,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25062,13 +25409,24 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ /* @internal */ - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -25099,7 +25457,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -25462,6 +25819,7 @@ var ts; var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; + var enumCount = 0; var symbolInstantiationDepth = 0; var emptyArray = []; var emptySymbols = ts.createMap(); @@ -25613,13 +25971,16 @@ var ts; // since we are only interested in declarations of the module itself return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, - getApparentType: getApparentType + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, + getBaseConstraintOfType: getBaseConstraintOfType, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); + var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -25702,11 +26063,13 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var emptyStringType = getLiteralType(""); + var zeroType = getLiteralType(0); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var suggestionCount = 0; + var maximumSuggestionCount = 10; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -25972,16 +26335,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26063,9 +26426,6 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } - function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; - } function isGlobalSourceFile(node) { return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -26073,7 +26433,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -26109,7 +26469,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26205,7 +26566,11 @@ var ts; // 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 // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + } + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; var propertyWithInvalidInitializer; @@ -26215,7 +26580,7 @@ var ts; loop: while (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 = getSymbol(location.locals, name, meaning)) { + if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { // symbol lookup restrictions for function-like declarations @@ -26286,12 +26651,12 @@ var ts; break; } } - if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { break loop; } break; case 232 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; @@ -26306,7 +26671,7 @@ var ts; if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -26316,7 +26681,7 @@ var ts; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -26351,7 +26716,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -26412,7 +26777,7 @@ var ts; result.isReferenced = true; } if (!result) { - result = getSymbol(globals, name, meaning); + result = lookup(globals, name, meaning); } if (!result) { if (nameNotFoundMessage) { @@ -26422,7 +26787,17 @@ var ts; !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + suggestionCount++; + error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), suggestion); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } } return undefined; @@ -26541,6 +26916,10 @@ var ts; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); @@ -26573,13 +26952,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -26595,7 +26974,7 @@ var ts; if (node.kind === 237 /* ImportEqualsDeclaration */) { return node; } - return ts.findAncestor(node, function (n) { return n.kind === 238 /* ImportDeclaration */; }); + return ts.findAncestor(node, ts.isImportDeclaration); } } function getDeclarationOfAliasSymbol(symbol) { @@ -26719,10 +27098,10 @@ var ts; function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); } - function getTargetOfExportSpecifier(node, dontResolveAlias) { + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); @@ -26738,7 +27117,7 @@ var ts; case 242 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 243 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 236 /* NamespaceExportDeclaration */: @@ -26887,7 +27266,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26909,6 +27288,11 @@ var ts; if (moduleName === undefined) { return; } + if (ts.startsWith(moduleReference, "@types/")) { + var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); + error(errorNode, diag, withoutAtTypePrefix, moduleReference); + } var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; @@ -26978,7 +27362,6 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); - symbol = undefined; } return symbol; } @@ -27128,7 +27511,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32 /* StringLiteral */, s); })); + return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started @@ -27458,34 +27841,59 @@ var ts; return result; } function typeToString(type, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + ts.Debug.assert(typeNode !== undefined, "should always get typenode?"); + var options = { removeComments: true }; + var writer = ts.createTextWriter(""); + var printer = ts.createPrinter(options, writer); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 4 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { - result = result.substr(0, maxLength - "...".length) + "..."; + return result.substr(0, maxLength - "...".length) + "..."; } return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 4 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 128 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 2048 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 32 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } } function createNodeBuilder() { - var context; return { typeToTypeNode: function (type, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { - context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind); + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; } @@ -27495,15 +27903,14 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags, encounteredError: false, - inObjectTypeLiteral: false, - checkAlias: true, symbolStack: undefined }; } - function typeToTypeNodeHelper(type) { + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; if (!type) { context.encounteredError = true; - // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)? return undefined; } if (type.flags & 1 /* Any */) { @@ -27518,23 +27925,25 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 16 /* Enum */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parentSymbol = getParentOfSymbol(type.symbol); + var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + } + if (type.flags & 272 /* EnumLike */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.text))); + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text))); + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 256 /* EnumLiteral */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } if (type.flags & 1024 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } @@ -27554,8 +27963,8 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.inObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; } } @@ -27566,39 +27975,31 @@ var ts; ts.Debug.assert(!!(type.flags & 32768 /* Object */)); return typeReferenceToTypeNode(type); } - if (objectFlags & 3 /* ClassOrInterface */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); - // TODO(aozgaa): handle type arguments. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); - } - if (type.flags & 16384 /* TypeParameter */) { - var name = symbolToName(type.symbol, /*expectsIdentifier*/ false); + if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (context.checkAlias && type.aliasSymbol) { - var name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false); - var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments); + if (!inTypeAlias && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var name = symbolToTypeReferenceName(type.aliasSymbol); + var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - context.checkAlias = false; - if (type.flags & 65536 /* Union */) { - var formattedUnionTypes = formatUnionTypes(type.types); - var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes); - if (unionTypeNodes && unionTypeNodes.length > 0) { - return ts.createUnionOrIntersectionTypeNode(166 /* UnionType */, unionTypeNodes); + if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { + var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context); + if (typeNodes && typeNodes.length > 0) { + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { context.encounteredError = true; } return undefined; } } - if (type.flags & 131072 /* Intersection */) { - return ts.createUnionOrIntersectionTypeNode(167 /* IntersectionType */, mapToTypeNodeArray(type.types)); - } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); // The type is an object literal type. @@ -27606,35 +28007,23 @@ var ts; } if (type.flags & 262144 /* Index */) { var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType); + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType); - var indexTypeNode = typeToTypeNodeHelper(type.indexType); + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); - function mapToTypeNodeArray(types) { - var result = []; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type_1 = types_1[_i]; - var typeNode = typeToTypeNodeHelper(type_1); - if (typeNode) { - result.push(typeNode); - } - } - return result; - } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var typeParameter = getTypeParameterFromMappedType(type); - var typeParameterNode = typeParameterToDeclaration(typeParameter); - var templateType = getTemplateTypeFromMappedType(type); - var templateTypeNode = typeToTypeNodeHelper(templateType); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); + var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; @@ -27643,14 +28032,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol); + return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); } else if (ts.contains(context.symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27696,41 +28085,53 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.createTypeLiteralNode(/*members*/ undefined); + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - return signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; } } - var saveInObjectTypeLiteral = context.inObjectTypeLiteral; - context.inObjectTypeLiteral = true; + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; var members = createTypeNodesFromResolvedType(resolved); - context.inObjectTypeLiteral = saveInObjectTypeLiteral; - return ts.createTypeLiteralNode(members); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol) { - var entityName = symbolToName(symbol, /*expectsIdentifier*/ false); + function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { + var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return ts.createTypeQueryNode(entityName); } + function symbolToTypeReferenceName(symbol) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType) { - var elementType = typeToTypeNodeHelper(typeArguments[0]); + if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + } + var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type))); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { context.encounteredError = true; } return undefined; @@ -27738,7 +28139,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = undefined; + var qualifiedName = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27751,48 +28152,72 @@ var ts; // 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)) { - var qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true); - if (!qualifiedName) { - qualifiedName = ts.createQualifiedName(qualifiedNamePart, /*right*/ undefined); + var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); + qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } else { - ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = qualifiedNamePart; - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); } } } } var entityName = undefined; - var nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); - qualifiedName.right = nameIdentifier; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); entityName = qualifiedName; } else { entityName = nameIdentifier; } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined; + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + if (typeArgumentNodes) { + var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; + lastIdentifier.typeArguments = undefined; + } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); } } + function addToQualifiedNameMissingRightIdentifier(left, right) { + ts.Debug.assert(left.right === undefined); + if (right.kind === 71 /* Identifier */) { + left.right = right; + return left; + } + var rightPart = right; + while (rightPart.left.kind !== 71 /* Identifier */) { + rightPart = rightPart.left; + } + left.right = rightPart.left; + rightPart.left = left; + return right; + } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); } var properties = resolvedType.properties; if (!properties) { @@ -27801,86 +28226,131 @@ var ts; for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { var propertySymbol = properties_2[_d]; var propertyType = getTypeOfSymbol(propertySymbol); - var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0]; - if (!oldDeclaration) { - return; - } - var propertyName = oldDeclaration.name; + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 67108864 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - // TODO(aozgaa): should we create a node with explicit or implict any? - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined)); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + typeElements.push(propertySignature); } } return typeElements.length ? typeElements : undefined; } } - function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) { + function mapToTypeNodes(types, context) { + if (ts.some(types)) { + var result = []; + for (var i = 0; i < types.length; ++i) { + var type = types[i]; + var typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + } + } + return result; + } + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { + var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 136 /* StringKeyword */ : 133 /* NumberKeyword */); - var name = ts.getNameFromIndexInfo(indexInfo); var indexingParameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type); - return ts.createIndexSignatureDeclaration( + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); }); - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); }); + function signatureToSignatureDeclarationHelper(signature, kind, context) { + var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + if (signature.thisParameter) { + var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + parameters.unshift(thisParameter); + } var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(); - var typeNode = typeToTypeNodeHelper(typePredicate.type); + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : + ts.createThisTypeNode(); + var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); } else { var returnType = getReturnTypeOfSignature(signature); - returnTypeNode = returnType && typeToTypeNodeHelper(returnType); + returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } - function typeParameterToDeclaration(type) { + function typeParameterToDeclaration(type, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter); - var name = symbolToName(type.symbol, /*expectsIdentifier*/ true); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol) { + function symbolToParameterDeclaration(parameterSymbol, context) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterType = getTypeOfSymbol(parameterSymbol); - var parameterTypeNode = typeToTypeNodeHelper(parameterType); - // TODO(aozgaa): In the future, check initializer accessibility. - var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(24 /* DotDotDotToken */), - // Clone name to remove trivia. - ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(55 /* QuestionToken */), parameterTypeNode, parameterDeclaration.initializer); + if (isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getNullableType(parameterType, 2048 /* Undefined */); + } + var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); return parameterNode; + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node) { + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); + if (clone.kind === 176 /* BindingElement */) { + clone.initializer = undefined; + } + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } } - function symbolToName(symbol, expectsIdentifier) { + function symbolToName(symbol, context, meaning, expectsIdentifier) { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && context.enclosingDeclaration) { - chain = getSymbolChain(symbol, 0 /* None */, /*endOfChain*/ true); + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -27888,19 +28358,18 @@ var ts; } if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); function createEntityNameFromSymbolChain(chain, index) { ts.Debug.assert(chain && 0 <= index && index < chain.length); - // const parentIndex = index - 1; var symbol = chain[index]; - var typeParameterString = ""; - if (index > 0) { + var typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { @@ -27909,20 +28378,10 @@ var ts; typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } - if (typeParameters && typeParameters.length > 0) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) { - context.encounteredError = true; - } - var writer = ts.getSingleLineStringWriter(); - var displayBuilder = getSymbolDisplayBuilder(); - displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0); - typeParameterString = writer.string(); - ts.releaseStringWriter(writer); - } + typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol); - var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName; - var identifier = ts.createIdentifier(symbolNameWithTypeParameters); + var symbolName = getNameOfSymbol(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -27954,28 +28413,29 @@ var ts; return [symbol]; } } - function getNameOfSymbol(symbol) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } + } + function getNameOfSymbol(symbol, context) { + var declaration = ts.firstOrUndefined(symbol.declarations); + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + return ts.declarationNameToString(declaration.parent.name); + } + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; } - return symbol.name; } + return symbol.name; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { @@ -27993,12 +28453,14 @@ var ts; flags |= t.flags; if (!(t.flags & 6144 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 65536 /* Union */) { + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } } } result.push(t); @@ -28034,13 +28496,14 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; } function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28097,7 +28560,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -28180,12 +28643,17 @@ var ts; else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -28541,7 +29009,7 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } @@ -28808,10 +29276,7 @@ var ts; exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 246 /* ExportSpecifier */) { - var exportSpecifier = node.parent; - exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? - getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -28954,7 +29419,7 @@ var ts; for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.name); - var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.name, prop); @@ -29070,7 +29535,7 @@ var ts; return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -29173,6 +29638,7 @@ var ts; var types = []; var definedInConstructor = false; var definedInMethod = false; + var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : @@ -29189,17 +29655,25 @@ var ts; definedInMethod = true; } } - if (expression.flags & 65536 /* JavaScriptFile */) { - // If there is a JSDoc type, use it - var type = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type && type !== unknownType) { - types.push(getWidenedType(type)); - continue; + // If there is a JSDoc type, use it + var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type_1) { + var declarationType = getWidenedType(type_1); + if (!jsDocType) { + jsDocType = declarationType; + } + else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { + var name = ts.getNameOfDeclaration(declaration); + error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); } } - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } } - return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor)); + var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding @@ -29449,7 +29923,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; } } } @@ -29512,7 +29986,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -29711,6 +30185,7 @@ var ts; return; } var baseTypeNode = getBaseTypeNodeOfClass(type); + var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && @@ -29718,7 +30193,7 @@ var ts; // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; @@ -29902,77 +30377,80 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { + function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { return !ts.isInAmbientContext(member); } - return expr.kind === 8 /* NumericLiteral */ || + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 71 /* Identifier */ && !!symbol.exports.get(expr.text); + expr.kind === 71 /* Identifier */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); } - function enumHasLiteralMembers(symbol) { + function getEnumKind(symbol) { + var links = getSymbolLinks(symbol); + if (links.enumKind !== undefined) { + return links.enumKind; + } + var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 232 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; + if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; } } } } - return true; + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } - function createEnumLiteralType(symbol, baseType, text) { - var type = createType(256 /* EnumLiteral */); - type.symbol = symbol; - type.baseType = baseType; - type.text = text; - return type; + function getBaseTypeOfEnumLiteralType(type) { + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = []; - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); - memberTypeList.push(memberType); - } - } + if (links.declaredType) { + return links.declaredType; + } + if (getEnumKind(symbol) === 1 /* Literal */) { + enumCount++; + var memberTypeList = []; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 232 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(memberType); } } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 65536 /* Union */; - enumType.types = memberTypeList; - unionTypes.set(getTypeListId(memberTypeList), enumType); + } + if (memberTypeList.length) { + var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 65536 /* Union */) { + enumType_1.flags |= 256 /* EnumLiteral */; + enumType_1.symbol = symbol; } + return links.declaredType = enumType_1; } } - return links.declaredType; + var enumType = createType(16 /* Enum */); + enumType.symbol = symbol; + return links.declaredType = enumType; } function getDeclaredTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 65536 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + if (!links.declaredType) { + links.declaredType = enumType; + } } return links.declaredType; } @@ -30219,7 +30697,7 @@ var ts; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -30306,8 +30784,8 @@ 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]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -30481,7 +30959,7 @@ var ts; // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = t.text; + var propName = t.value; var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); @@ -30613,6 +31091,27 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createMap(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190 /* Primitive */) { + continue; + } + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var name = _c[_b].name; + if (!props.has(name)) { + props.set(name, createUnionOrIntersectionProperty(type, name)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : @@ -30674,8 +31173,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type_2 = types_2[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -30731,7 +31230,7 @@ var ts; var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : @@ -30746,12 +31245,12 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { @@ -30823,7 +31322,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -31231,8 +31730,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -31367,8 +31867,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_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -31399,7 +31899,7 @@ var ts; return ts.length(type.target.typeParameters); } // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol) { + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { @@ -31414,7 +31914,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -31437,7 +31937,7 @@ var ts; // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -31449,7 +31949,6 @@ var ts; : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { @@ -31489,14 +31988,15 @@ var ts; return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { return unknownType; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getTypeFromClassOrInterfaceReference(node, symbol); + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { - return getTypeFromTypeAliasReference(node, symbol); + return getTypeFromTypeAliasReference(node, symbol, typeArguments); } if (symbol.flags & 107455 /* Value */ && node.kind === 277 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In @@ -31559,10 +32059,7 @@ var ts; ? node.expression : undefined; symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - type = symbol === unknownSymbol ? unknownType : - symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + type = getTypeReferenceType(node, symbol); } // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the // type reference in checkTypeReferenceOrExpressionWithTypeArguments. @@ -31571,6 +32068,9 @@ var ts; } return links.resolvedType; } + function typeArgumentsFromTypeReferenceNode(node) { + return ts.map(node.typeArguments, getTypeFromTypeNode); + } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -31812,14 +32312,14 @@ 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, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31827,8 +32327,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -31959,8 +32459,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 addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, type); } } @@ -32024,9 +32524,9 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? neverType : - getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + getLiteralType(ts.unescapeIdentifier(prop.name)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); @@ -32056,12 +32556,12 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? - indexType.text : + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + "" + indexType.value : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : undefined; - if (propName) { + if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { @@ -32076,11 +32576,11 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { @@ -32105,7 +32605,7 @@ var ts; if (accessNode) { var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -32258,7 +32758,7 @@ var ts; var rightProp = _a[_i]; // we approximate own properties as non-methods plus methods that are inside the object literal var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.name, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -32275,11 +32775,11 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { + if (rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -32306,15 +32806,16 @@ var ts; function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } - function createLiteralType(flags, text) { + function createLiteralType(flags, value, symbol) { var type = createType(flags); - type.text = text; + type.symbol = symbol; + type.value = value; return type; } function getFreshTypeOfLiteralType(type) { if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32325,11 +32826,17 @@ var ts; function getRegularTypeOfLiteralType(type) { return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - var type = map.get(text); + function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. + var qualifier = typeof value === "number" ? "#" : "@"; + var key = enumId ? enumId + qualifier + value : qualifier + value; + var type = literalTypes.get(key); if (!type) { - map.set(text, type = createLiteralType(flags, text)); + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; } @@ -32593,7 +33100,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (getCheckFlags(symbol) & 1 /* Instantiated */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { var links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases @@ -33087,29 +33594,27 @@ var ts; type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { return true; } - var id = source.id + "," + target.id; + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); if (relation !== undefined) { return relation; } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { + if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { enumRelation.set(id, false); return false; } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var targetEnumType = getTypeOfSymbol(targetSymbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; if (property.flags & 8 /* EnumMember */) { var targetProperty = getPropertyOfType(targetEnumType, property.name); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33120,42 +33625,50 @@ var ts; return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + if (t & 1 /* Any */ || s & 8192 /* Never */) return true; - if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) + if (s & 262178 /* StringLike */ && t & 2 /* String */) return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + if (s & 84 /* NumberLike */ && t & 4 /* Number */) return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { + if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + if (s & 224 /* Literal */ && t & 224 /* Literal */ && + source.value === target.value && + isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) + return true; + } + if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) return true; - if (source.flags & 32768 /* Object */ && target.flags & 16777216 /* NonPrimitive */) + if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) + if (s & 1 /* Any */) return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } } return false; } @@ -33378,29 +33891,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33789,10 +34279,10 @@ var ts; } } else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -33901,24 +34391,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34038,7 +34542,7 @@ var ts; // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. function forEachProperty(prop, callback) { - if (getCheckFlags(prop) & 6 /* Synthetic */) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.name); @@ -34065,13 +34569,13 @@ var ts; } // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is the constructor type for an abstract class @@ -34120,8 +34624,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -34215,8 +34719,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } @@ -34224,8 +34728,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_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34251,7 +34755,7 @@ var ts; return getUnionType(types, /*subtypeReduction*/ true); } var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -34299,27 +34803,27 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -34331,8 +34835,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_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -34342,35 +34846,35 @@ var ts; // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : type.flags & 7406 /* PossiblyFalsy */; } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { - return type; - } - var types = [type]; - if (flags & 262178 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) - types.push(voidType); - if (flags & 2048 /* Undefined */) - types.push(undefinedType); - if (flags & 4096 /* Null */) - types.push(nullType); - return getUnionType(types); - } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : type; } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 2 /* String */ ? emptyStringType : + type.flags & 4 /* Number */ ? zeroType : + type.flags & 8 /* Boolean */ || type === falseType ? falseType : + type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & 32 /* StringLiteral */ && type.value === "" || + type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + neverType; + } + function getNullableType(type, flags) { + var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + return missing === 0 ? type : + missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + getUnionType([type, undefinedType, nullType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } @@ -34537,7 +35041,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -34622,7 +35126,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - var members = createSymbolTable(properties); + var members = ts.createMap(); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var prop = properties_5[_i]; var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); @@ -34655,20 +35159,10 @@ var ts; inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); } function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var sourceStack; - var targetStack; - var depth = 0; + var symbolStack; + var visited; var inferiority = 0; - var visited = ts.createMap(); inferFromTypes(originalSource, originalTarget); - function isInProcess(source, target) { - for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) { - return true; - } - } - return false; - } function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; @@ -34683,7 +35177,7 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. @@ -34800,26 +35294,29 @@ var ts; else { source = getApparentType(source); if (source.flags & 32768 /* Object */) { - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) { - return; - } var key = source.id + "," + target.id; - if (visited.get(key)) { + if (visited && visited.get(key)) { return; } - visited.set(key, true); - if (depth === 0) { - sourceStack = []; - targetStack = []; + (visited || (visited = ts.createMap())).set(key, true); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 32768 /* Object */ && + !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (ts.contains(symbolStack, symbol)) { + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypes(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypes(source, target); } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromObjectTypes(source, target); - depth--; } } } @@ -34908,8 +35405,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35005,7 +35502,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35018,11 +35515,13 @@ var ts; // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35091,7 +35590,7 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } @@ -35154,8 +35653,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -35173,15 +35672,16 @@ var ts; return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; return strictNullChecks ? - type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type.text === "0"; + if (flags & 64 /* NumberLiteral */) { + var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; @@ -35388,7 +35888,7 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); @@ -35414,8 +35914,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35495,8 +35995,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35527,7 +36027,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -35553,7 +36053,7 @@ var ts; function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } var visitedFlowStart = visitedFlowCount; @@ -35695,7 +36195,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36202,6 +36702,26 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } + function isApparentTypePosition(node) { + var parent = node.parent; + return parent.kind === 179 /* PropertyAccessExpression */ || + parent.kind === 181 /* CallExpression */ && parent.expression === node || + parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + } + function typeHasNullableConstraint(type) { + return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + } + function getDeclaredOrApparentType(symbol, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. + var type = getTypeOfSymbol(symbol); + if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getApparentType); + } + return type; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36268,7 +36788,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); var declaration = localOrExportSymbol.valueDeclaration; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36309,7 +36829,7 @@ var ts; ts.isInAmbientContext(declaration); var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - includeFalsyTypes(type, 2048 /* Undefined */); + getNullableType(type, 2048 /* Undefined */); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -36317,7 +36837,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37214,8 +37734,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var current = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { @@ -37329,7 +37849,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -37367,7 +37887,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -37518,6 +38038,8 @@ var ts; if (spread.flags & 32768 /* Object */) { // only set the symbol and flags if this is a (fresh) object type spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; spread.symbol = node.symbol; } return spread; @@ -37596,6 +38118,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37613,6 +38139,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37622,39 +38151,39 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { + attributesTable = ts.createMap(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; if (!filter || filter(attr)) { attributesTable.set(attr.name, attr); } - }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = []; - for (var _b = 0, _c = parent.children; _b < _c.length; _b++) { - var child = _c[_b]; + for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { + var child = _d[_c]; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. if (child.kind === 10 /* JsxText */) { @@ -37666,11 +38195,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37681,7 +38210,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37689,8 +38223,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37768,7 +38301,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37820,6 +38364,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37840,6 +38398,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37878,6 +38437,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -37947,7 +38507,7 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.text; + var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -38152,6 +38712,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38180,7 +38768,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38200,29 +38801,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; } - function getDeclarationModifierFlagsFromSymbol(s) { - if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; - } - if (getCheckFlags(s) & 6 /* Synthetic */) { - var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : - 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; - return accessModifier | staticModifier; - } - if (s.flags & 16777216 /* Prototype */) { - return 4 /* Public */ | 32 /* Static */; - } - return 0; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); } /** * Check whether the requested property access is valid. @@ -38233,11 +38816,11 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkPropertyAccessibility(node, left, type, prop) { - var flags = getDeclarationModifierFlagsFromSymbol(prop); + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? node.name : node.right; - if (getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 256 /* 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; @@ -38335,42 +38918,6 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } - function markPropertyAsReferenced(prop) { - if (prop && - noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (getCheckFlags(prop) & 1 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } - } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -38407,7 +38954,7 @@ var ts; markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); + var propType = getDeclaredOrApparentType(prop, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { @@ -38426,6 +38973,126 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); + if (suggestion) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function getSuggestionForNonexistentProperty(node, containingType) { + var suggestion = getSpellingSuggestionForName(node.text, getPropertiesOfObjectType(containingType), 107455 /* Value */); + return suggestion && suggestion.name; + } + function getSuggestionForNonexistentSymbol(location, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var symbol = getSymbol(symbols, name, meaning); + if (symbol) { + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol; + } + return getSpellingSuggestionForName(name, ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.name; + } + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. + */ + function getSpellingSuggestionForName(name, symbols, meaning) { + var worstDistance = name.length * 0.4; + var maximumLengthDifference = Math.min(3, name.length * 0.34); + var bestDistance = Number.MAX_VALUE; + var bestCandidate = undefined; + if (name.length > 30) { + return undefined; + } + name = name.toLowerCase(); + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var candidate = symbols_3[_i]; + if (candidate.flags & meaning && + candidate.name && + Math.abs(candidate.name.length - name.length) < maximumLengthDifference) { + var candidateName = candidate.name.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (candidateName.length < 3 || + name.length < 3 || + candidateName === "eval" || + candidateName === "intl" || + candidateName === "undefined" || + candidateName === "map" || + candidateName === "nan" || + candidateName === "set") { + continue; + } + var distance = ts.levenshtein(name, candidateName); + if (distance > worstDistance) { + continue; + } + if (distance < 3) { + return candidate; + } + else if (distance < bestDistance) { + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } + function isInPropertyInitializer(node) { + while (node) { + if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -38548,7 +39215,16 @@ var ts; } return true; } + function callLikeExpressionMayHaveTypeArguments(node) { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) + return ts.isCallOrNewExpression(node); + } function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. + ts.forEach(node.typeArguments, checkSourceElement); + } if (node.kind === 183 /* TaggedTemplateExpression */) { checkExpression(node.template); } @@ -38579,8 +39255,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -38688,7 +39364,7 @@ var ts; // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex); + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -39059,7 +39735,7 @@ var ts; case 71 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { @@ -39169,7 +39845,7 @@ var ts; return arg; } } - function resolveCall(node, signatures, candidatesOutArray, headMessage) { + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; var isDecorator = node.kind === 147 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -39199,7 +39875,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -39300,7 +39976,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -39308,14 +39984,45 @@ var ts; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (headMessage) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + if (fallbackError) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); } reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); } } - else { - reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min < max ? min + "-" + max : min; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + } + else if (args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; + min = Math.min(min, sig.minArgumentCount); + max = Math.max(max, sig.parameters.length); + } + var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + var paramCount = hasRestParameter_1 ? min : + min < max ? min + "-" + max : + min; + var argCount = args.length - (hasSpreadArgument ? 1 : 0); + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1; + diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } // 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 that anySignature. @@ -39323,8 +40030,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { - var candidate = candidates_1[_i]; + for (var _b = 0, candidates_1 = candidates; _b < candidates_1.length; _b++) { + var candidate = candidates_1[_b]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -39334,14 +40041,6 @@ var ts; } } return resolveErrorCall(node); - function reportError(message, arg0, arg1, arg2) { - var errorInfo; - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - if (headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - } function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -39509,7 +40208,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39676,8 +40375,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var type = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -39854,7 +40553,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return getNullableType(type, 2048 /* Undefined */); } } return type; @@ -39920,11 +40619,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -40055,7 +40754,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40251,7 +40950,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40278,7 +40977,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { 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); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40291,7 +40990,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -40304,8 +41003,8 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || - symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */); @@ -40392,7 +41091,7 @@ var ts; return silentNeverType; } if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } switch (node.operator) { case 37 /* PlusToken */: @@ -40439,8 +41138,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40457,8 +41156,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var t = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -40467,8 +41166,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_21 = types; _a < types_21.length; _a++) { - var t = types_21[_a]; + for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { + var t = types_20[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -40513,7 +41212,7 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { @@ -40808,7 +41507,7 @@ var ts; rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; @@ -40868,7 +41567,7 @@ var ts; return checkInExpression(left, right, leftType, rightType); case 53 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? @@ -40961,12 +41660,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41012,9 +41714,9 @@ var ts; } switch (node.kind) { case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; case 86 /* FalseKeyword */: @@ -41079,7 +41781,7 @@ var ts; } contextualType = constraint; } - return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); } return false; } @@ -41424,17 +42126,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41457,7 +42160,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41476,7 +42179,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41595,7 +42298,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41683,7 +42386,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41840,7 +42544,7 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -41883,7 +42587,7 @@ var ts; } // Check if we're indexing with a numeric type and the object type is a generic // type with a constraint that has a numeric index signature. - if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 340 /* NumberLike */)) { + if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 84 /* NumberLike */)) { var constraint = getBaseConstraintOfType(objectType); if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { return type; @@ -41943,16 +42647,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41963,7 +42667,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42087,7 +42791,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42101,8 +42805,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42160,12 +42864,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42480,7 +43185,9 @@ var ts; * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node) { - var typeName = node && ts.getEntityNameFromTypeNode(node); + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { var rootName = typeName && getFirstIdentifier(typeName); var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol @@ -42490,6 +43197,57 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + var entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && ts.isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference(entityName); + } + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 167 /* IntersectionType */: + case 166 /* UnionType */: + var commonEntityName = void 0; + for (var _i = 0, _a = node.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here + return undefined; + } + if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object + if (!ts.isIdentifier(commonEntityName) || + !ts.isIdentifier(individualEntityName) || + commonEntityName.text !== individualEntityName.text) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } function getParameterTypeNodeForDecoratorCheck(node) { return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } @@ -42520,7 +43278,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -42529,15 +43287,15 @@ var ts; case 154 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; case 149 /* PropertyDeclaration */: - markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); break; case 146 /* Parameter */: - markTypeNodeAsReferenced(node.type); + markDecoratorMedataDataTypeNodeAsReferenced(node.type); break; } } @@ -42671,15 +43429,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42759,7 +43518,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42827,7 +43586,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42841,7 +43600,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43107,7 +43866,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43222,11 +43981,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43609,7 +44371,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43831,13 +44593,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44076,7 +44841,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -44109,7 +44874,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -44132,15 +44897,11 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { - // value of 'static' is not the same for properties - not override, skip it - continue; - } if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; @@ -44160,7 +44921,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44247,97 +45008,88 @@ var ts; function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); - var autoValue = 0; // set to undefined when enum member is non-constant - var ambient = ts.isInAmbientContext(node); - var enumIsConst = ts.isConst(node); + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (isComputedNonLiteralName(member.name)) { - error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); - } - else { - var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); - } - } - var previousEnumMemberIsNonConstant = autoValue === undefined; - var initializer = member.initializer; - if (initializer) { - autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); - } - else if (ambient && !enumIsConst) { - // In ambient enum declarations that specify no const modifier, enum member declarations - // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). - autoValue = undefined; - } - else if (previousEnumMemberIsNonConstant) { - // If the member declaration specifies no value, the member is considered a constant enum member. - // If the member is the first member in the enum declaration, it is assigned the value zero. - // Otherwise, it is assigned the value of the immediately preceding member plus one, - // and an error occurs if the immediately preceding member is not a constant enum member - error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); - } - if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue; - autoValue++; - } + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; } - nodeLinks.flags |= 16384 /* EnumValuesComputed */; } - function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { - // Controls if error should be reported after evaluation of constant value is completed - // Can be false if another more precise error was already reported during evaluation. - var reportError = true; - var value = evalConstant(initializer); - if (reportError) { - if (value === undefined) { - if (enumIsConst) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (ambient) { - error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); - } - else { - // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(value)) { - error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } + } + function computeMemberValue(member, autoValue) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else { + var text = ts.getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - return value; - function evalConstant(e) { - switch (e.kind) { - case 192 /* PrefixUnaryExpression */: - var value_1 = evalConstant(e.operand); - if (value_1 === undefined) { - return undefined; - } - switch (e.operator) { + } + if (member.initializer) { + return computeConstantValue(member); + } + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + return undefined; + } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. + if (autoValue !== undefined) { + return autoValue; + } + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + return undefined; + } + function computeConstantValue(member) { + var enumKind = getEnumKind(getSymbolOfNode(member.parent)); + var isConstEnum = ts.isConst(member.parent); + var initializer = member.initializer; + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + if (value !== undefined) { + if (isConstEnum && typeof value === "number" && !isFinite(value)) { + error(initializer, isNaN(value) ? + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + else if (enumKind === 1 /* Literal */) { + error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); + return 0; + } + else if (isConstEnum) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ts.isInAmbientContext(member.parent)) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + 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); + } + return value; + function evaluate(expr) { + switch (expr.kind) { + case 192 /* PrefixUnaryExpression */: + var value_1 = evaluate(expr.operand); + if (typeof value_1 === "number") { + switch (expr.operator) { case 37 /* PlusToken */: return value_1; case 38 /* MinusToken */: return -value_1; case 52 /* TildeToken */: return ~value_1; } - return undefined; - case 194 /* BinaryExpression */: - var left = evalConstant(e.left); - if (left === undefined) { - return undefined; - } - var right = evalConstant(e.right); - if (right === undefined) { - return undefined; - } - switch (e.operatorToken.kind) { + } + break; + case 194 /* BinaryExpression */: + var left = evaluate(expr.left); + var right = evaluate(expr.right); + if (typeof left === "number" && typeof right === "number") { + switch (expr.operatorToken.kind) { case 49 /* BarToken */: return left | right; case 48 /* AmpersandToken */: return left & right; case 46 /* GreaterThanGreaterThanToken */: return left >> right; @@ -44350,81 +45102,53 @@ var ts; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; } - return undefined; - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(e); - return +e.text; - case 185 /* ParenthesizedExpression */: - return evalConstant(e.expression); - case 71 /* Identifier */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType_1; - var propertyName = void 0; - if (e.kind === 71 /* Identifier */) { - // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. - // instead pick current enum type and later try to fetch member from the type - enumType_1 = currentType; - propertyName = e.text; + } + break; + case 9 /* StringLiteral */: + return expr.text; + case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(expr); + return +expr.text; + case 185 /* ParenthesizedExpression */: + return evaluate(expr.expression); + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.text); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = expr.kind === 179 /* PropertyAccessExpression */ ? + expr.name.text : + expr.argumentExpression.text; + return evaluateEnumMember(expr, type.symbol, name); } - else { - var expression = void 0; - if (e.kind === 180 /* ElementAccessExpression */) { - if (e.argumentExpression === undefined || - e.argumentExpression.kind !== 9 /* StringLiteral */) { - return undefined; - } - expression = e.expression; - propertyName = e.argumentExpression.text; - } - else { - expression = e.expression; - propertyName = e.name.text; - } - // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - var current = expression; - while (current) { - if (current.kind === 71 /* Identifier */) { - break; - } - else if (current.kind === 179 /* PropertyAccessExpression */) { - current = current.expression; - } - else { - return undefined; - } - } - enumType_1 = getTypeOfExpression(expression); - // allow references to constant members of other enums - if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { - return undefined; - } - } - if (propertyName === undefined) { - return undefined; - } - var property = getPropertyOfObjectType(enumType_1, propertyName); - if (!property || !(property.flags & 8 /* EnumMember */)) { - return undefined; - } - var propertyDecl = property.valueDeclaration; - // self references are illegal - if (member === propertyDecl) { - return undefined; - } - // illegal case: forward reference - if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { - reportError = false; - error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); - return undefined; - } - return getNodeLinks(propertyDecl).enumMemberValue; + } + break; + } + return undefined; + } + function evaluateEnumMember(expr, enumSymbol, name) { + var memberSymbol = enumSymbol.exports.get(name); + if (memberSymbol) { + var declaration = memberSymbol.valueDeclaration; + if (declaration !== member) { + if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + return getNodeLinks(declaration).enumMemberValue; + } + 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; } } + return undefined; } } + function isConstantMemberAccess(node) { + return node.kind === 71 /* Identifier */ || + node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9 /* StringLiteral */; + } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; @@ -44455,7 +45179,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -44714,6 +45438,10 @@ var ts; ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. + if (node.kind === 246 /* ExportSpecifier */ && compilerOptions.isolatedModules && !(target.flags & 107455 /* Value */)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } } } function checkImportBinding(node) { @@ -45389,6 +46117,10 @@ var ts; return entityNameSymbol; } } + if (entityName.parent.kind === 286 /* JSDocParameterTag */) { + var parameter = ts.getParameterFromJSDoc(entityName.parent); + return parameter && parameter.symbol; + } if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { // Missing entity name. @@ -45436,7 +46168,7 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } @@ -45564,7 +46296,7 @@ var ts; var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } - if (ts.isDeclarationName(node)) { + if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -45654,16 +46386,16 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_3 = []; + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { var symbol = getPropertyOfType(t, name_2); if (symbol) { - symbols_3.push(symbol); + symbols_4.push(symbol); } }); - return symbols_3; + return symbols_4; } else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { @@ -45981,7 +46713,7 @@ var ts; else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } else if (isTypeOfKind(type, 262178 /* StringLike */)) { @@ -46010,7 +46742,7 @@ var ts; ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; if (flags & 4096 /* AddUndefined */) { - type = includeFalsyTypes(type, 2048 /* Undefined */); + type = getNullableType(type, 2048 /* Undefined */); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -46022,15 +46754,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46116,7 +46839,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46284,7 +47006,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46311,9 +47033,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -47419,6 +48142,19 @@ var ts; } } ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + if (name.parent.propertyName) { + return true; + } + // falls through + default: + return ts.isDeclarationName(name); + } + } })(ts || (ts = {})); /// /// @@ -47556,53 +48292,63 @@ var ts; if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { return node; } - switch (node.kind) { - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 298 /* EndOfDeclarationMarker */: - case 247 /* MissingDeclaration */: - // No need to visit nodes with no children. - return node; + switch (kind) { // Names + case 71 /* Identifier */: + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 143 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - // Signatures and Signature Elements - case 160 /* FunctionType */: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 155 /* CallSignature */: - return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: - return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 150 /* MethodSignature */: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 157 /* IndexSignature */: - return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + // Signature elements + case 145 /* TypeParameter */: + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 146 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 147 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + // Type elements + case 148 /* PropertySignature */: + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 149 /* PropertyDeclaration */: + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + case 150 /* MethodSignature */: + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + case 151 /* MethodDeclaration */: + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 152 /* Constructor */: + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 153 /* GetAccessor */: + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + case 154 /* SetAccessor */: + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + case 155 /* CallSignature */: + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 156 /* ConstructSignature */: + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 157 /* IndexSignature */: + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 159 /* TypeReference */: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 158 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + case 159 /* TypeReference */: + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + case 160 /* FunctionType */: + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + case 161 /* ConstructorType */: + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 163 /* TypeLiteral */: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 164 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 165 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 166 /* UnionType */: + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 167 /* IntersectionType */: - return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); case 170 /* TypeOperator */: @@ -47613,22 +48359,6 @@ var ts; return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 173 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - // Type Declarations - case 145 /* TypeParameter */: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - // Type members - case 148 /* PropertySignature */: - return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* MethodDeclaration */: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); // Binding patterns case 174 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); @@ -47667,12 +48397,12 @@ var ts; return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); case 192 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 193 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 194 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: @@ -47689,6 +48419,8 @@ var ts; return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 203 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 204 /* MetaProperty */: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc case 205 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); @@ -47735,6 +48467,10 @@ var ts; return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 229 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + case 230 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + case 231 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitNode(node.type, visitor, ts.isTypeNode)); case 232 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 233 /* ModuleDeclaration */: @@ -47743,6 +48479,8 @@ var ts; return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 235 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 236 /* NamespaceExportDeclaration */: + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 237 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 238 /* ImportDeclaration */: @@ -47769,8 +48507,6 @@ var ts; // JSX case 249 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxAttributes */: - return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 250 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 251 /* JsxOpeningElement */: @@ -47779,6 +48515,8 @@ var ts; return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 253 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 254 /* JsxAttributes */: + return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 255 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 256 /* JsxExpression */: @@ -47808,7 +48546,10 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 297 /* CommaListExpression */: + return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: + // No need to visit nodes with no children. return node; } } @@ -47884,6 +48625,13 @@ var ts; result = reduceNode(node.expression, cbNode, result); break; // Type member + case 148 /* PropertySignature */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.questionToken, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; case 149 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); @@ -48234,6 +48982,9 @@ var ts; case 296 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; + case 297 /* CommaListExpression */: + result = reduceNodes(node.elements, cbNodes, result); + break; default: break; } @@ -48856,7 +49607,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -50275,21 +51026,17 @@ var ts; return ts.createIdentifier("Object"); } function serializeUnionOrIntersectionType(node) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isVoidExpression(serializedIndividual)) { - // If we dont have any other type already set, set the initial type - if (!serializedUnion) { - serializedUnion = serializedIndividual; - } - } - else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } - else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) { + else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || @@ -50819,7 +51566,12 @@ var ts; // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes // old emitter always generate 'expression' part of the name as-is. var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); - return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member); + var valueExpression = transformEnumMemberDeclarationValue(member); + var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); + var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? + innerAssignment : + ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); + return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -50894,10 +51646,12 @@ var ts; * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { - // Emit a variable statement for the module. - var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ]); + ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -51154,7 +51908,7 @@ var ts; function visitExportDeclaration(node) { if (!node.exportClause) { // Elide a star export if the module it references does not export a value. - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -51583,7 +52337,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -51920,7 +52674,7 @@ var ts; var enclosingSuperContainerFlags = 0; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -51988,21 +52742,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52152,6 +52900,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52159,24 +52910,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52187,13 +52935,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52479,12 +53221,22 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + 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 };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; @@ -52498,11 +53250,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + 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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -52532,7 +53284,7 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -53017,7 +53769,7 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } return ts.visitEachChild(node, visitor, context); @@ -53224,7 +53976,7 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } currentSourceFile = node; @@ -54502,12 +55254,13 @@ var ts; } else { assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 26 /* CommaToken */, acc); })), node); + updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -55842,7 +56595,7 @@ var ts; if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; @@ -56276,8 +57029,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } currentSourceFile = node; @@ -58730,7 +59482,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } currentSourceFile = node; @@ -59025,9 +59777,9 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: // This visitor does not descend into the tree, as export/import statements @@ -59826,9 +60578,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (ts.isDeclarationFile(node) - || !(ts.isExternalModule(node) - || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60716,9 +61466,9 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 298 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 299 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringVisitor(node); @@ -61200,7 +61950,7 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { - if (ts.isDeclarationFile(node)) { + if (node.isDeclarationFile) { return node; } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { @@ -61363,7 +62113,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(300 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -61428,7 +62178,7 @@ var ts; dispose: dispose }; function transformRoot(node) { - return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node; + return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } /** * Enables expression substitutions in the pretty printer for the provided SyntaxKind. @@ -62377,7 +63127,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62413,11 +63163,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62844,12 +63594,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62862,24 +63611,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62891,12 +63646,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62969,7 +63718,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63206,7 +63955,7 @@ var ts; var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); - write(enumMemberValue.toString()); + write(ts.getTextOfConstantValue(enumMemberValue)); } write(","); writeLine(); @@ -63305,7 +64054,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63317,12 +64066,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63339,7 +64082,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63354,6 +64097,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63361,15 +64117,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63390,7 +64153,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -63449,7 +64212,8 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) { + else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || + (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -63458,7 +64222,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -63668,6 +64432,11 @@ var ts; write("["); } else { + if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + write("();"); + writeLine(); + return; + } // Construct signature or constructor type write new Signature if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { write("new "); @@ -63974,7 +64743,7 @@ var ts; function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; - if (ts.isDeclarationFile(referencedFile)) { + if (referencedFile.isDeclarationFile) { // Declaration file, use declaration file name declFileName = referencedFile.fileName; } @@ -64158,7 +64927,7 @@ var ts; for (var i = 0; i < numNodes; i++) { var currentNode = bundle ? bundle.sourceFiles[i] : node; var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; var helpers = ts.getEmitHelpers(currentNode); if (helpers) { @@ -64195,7 +64964,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -64283,7 +65052,9 @@ var ts; return text; } function print(hint, node, sourceFile) { - setSourceFile(sourceFile); + if (sourceFile) { + setSourceFile(sourceFile); + } pipelineEmitWithNotification(hint, node); } function setSourceFile(sourceFile) { @@ -64362,7 +65133,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenText(kind); + writeTokenNode(node); return; } switch (kind) { @@ -64580,7 +65351,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenText(kind); + writeTokenNode(node); return; } } @@ -64603,7 +65374,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: - writeTokenText(kind); + writeTokenNode(node); return; // Expressions case 177 /* ArrayLiteralExpression */: @@ -64668,6 +65439,8 @@ var ts; // Transformation nodes case 296 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* CommaListExpression */: + return emitCommaList(node); } } function trySubstituteNode(hint, node) { @@ -64706,6 +65479,7 @@ var ts; // function emitIdentifier(node) { write(getTextOfNode(node, /*includeTrivia*/ false)); + emitTypeArguments(node, node.typeArguments); } // // Names @@ -64734,6 +65508,7 @@ var ts; function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); + emitWithPrefix(" = ", node.default); } function emitParameter(node) { emitDecorators(node, node.decorators); @@ -64854,7 +65629,10 @@ var ts; } function emitTypeLiteral(node) { write("{"); - emitList(node, node.members, 65 /* TypeLiteralMembers */); + // If the literal is empty, do not add spaces between braces. + if (node.members.length > 0) { + emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); + } write("}"); } function emitArrayType(node) { @@ -64892,9 +65670,15 @@ var ts; write("]"); } function emitMappedType(node) { + var emitFlags = ts.getEmitFlags(node); write("{"); - writeLine(); - increaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + increaseIndent(); + } writeIfPresent(node.readonlyToken, "readonly "); write("["); emit(node.typeParameter.name); @@ -64905,8 +65689,13 @@ var ts; write(": "); emit(node.type); write(";"); - writeLine(); - decreaseIndent(); + if (emitFlags & 1 /* SingleLine */) { + write(" "); + } + else { + writeLine(); + decreaseIndent(); + } write("}"); } function emitLiteralType(node) { @@ -64922,7 +65711,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); + emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); write("}"); } } @@ -65006,7 +65795,7 @@ var ts; // check if constant enum value is integer var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; } @@ -65109,7 +65898,7 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); - writeTokenText(node.operatorToken.kind); + writeTokenNode(node.operatorToken); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -65837,6 +66626,9 @@ var ts; function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } + function emitCommaList(node) { + emitExpressionList(node, node.elements, 272 /* CommaListElements */); + } /** * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. @@ -66118,6 +66910,15 @@ var ts; ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) : writeTokenText(token, pos); } + function writeTokenNode(node) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writeTokenText(node.kind); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); @@ -66300,7 +67101,9 @@ var ts; if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : + "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { return getLiteralTextOfNode(textSourceNode); @@ -66580,14 +67383,17 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 272] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElementsWithSpaceBetweenBraces"] = 432] = "ObjectBindingPatternElementsWithSpaceBetweenBraces"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; @@ -66814,6 +67620,90 @@ var ts; return output; } ts.formatDiagnostics = formatDiagnostics; + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; + case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; + case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + } + } + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + // 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) { + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + 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. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + } + var categoryColor = getCategoryFormat(diagnostic.category); + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -66863,6 +67753,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; + var modifiedFilePaths; var cachedSemanticDiagnosticsForFile = {}; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); @@ -66919,7 +67810,8 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; - if (!tryReuseStructureFromOldProgram()) { + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); @@ -66978,7 +67870,8 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67016,76 +67909,100 @@ var ts; return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (!oldProgramState && !file.ambientModuleNames.length) { - // if old program state is not supplied and file does not contain locally defined ambient modules - // then the best we can do is fallback to the default logic + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile); } - // at this point we know that either + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occured during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules - // OR // - old program state is available - // OR - // - both of items above - // With this it is possible that we can tell how some module names from the initial list will be resolved - // without doing actual resolution (in particular if some name was resolved to ambient module). - // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` - // since we don't want to resolve them again. - // this is a list of modules for which we cannot predict resolution so they should be actually resolved + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ var unknownModuleNames; - // this is a list of combined results assembles from predicted and resolved results. - // Order in this list matches the order in the original list of module names `moduleNames` which is important - // so later we can split results to resolutions of modules and resolutions of module augmentations. + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ var result; - // a transient placeholder that is used to mark predicted resolution in the result list + /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // module name is known to be resolved to ambient module if - // - module name is contained in the list of ambient modules that are locally declared in the file - // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // If we want to reuse resolutions more aggressively, we can refine this to check for whether the + // text of the corresponding modulenames has changed. + if (file === oldSourceFile) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file // (so the same module declaration will land in the new program) - var isKnownToResolveToAmbientModule = false; + var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { - isKnownToResolveToAmbientModule = true; + resolvesToAmbientModuleInNonModifiedFile = true; if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); } } else { - isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); } - if (isKnownToResolveToAmbientModule) { - if (!unknownModuleNames) { - // found a first module name for which result can be prediced - // this means that this module name should not be passed to `resolveModuleNamesWorker`. - // We'll use a separate list for module names that are definitely unknown. - result = new Array(moduleNames.length); - // copy all module names that appear before the current one in the list - // since they are known to be unknown - unknownModuleNames = moduleNames.slice(0, i); - } - // mark prediced resolution in the result list - result[i] = predictedToResolveToAmbientModuleMarker; + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } - else if (unknownModuleNames) { - // found unknown module name and we are already using separate list for those - add it to the list - unknownModuleNames.push(moduleName); + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } - if (!unknownModuleNames) { - // we've looked throught the list but have not seen any predicted resolution - // use default logic - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var resolutions = unknownModuleNames.length + var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) : emptyArray; - // combine results of resolutions and predicted results + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } var j = 0; for (var i = 0; i < result.length; i++) { - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } } else { result[i] = resolutions[j]; @@ -67094,16 +68011,15 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; - function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - if (!oldProgramState) { - return false; - } + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { // module used to be resolved to file - ignore it return false; } - var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } @@ -67123,84 +68039,90 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return false; + return 0 /* Not */; } // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } - ts.Debug.assert(!oldProgram.structureIsReused); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); // there is an old program, check if we can reuse its structure var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { - return false; + return oldProgram.structureIsReused = 0 /* Not */; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { + // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check tripleslash references if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } - else { - // file has no changes - use it as is - newSourceFile = oldSourceFile; - } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } - var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); // try to verify results of module resolution for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; } } if (resolveTypeReferenceDirectiveNamesWorker) { @@ -67209,12 +68131,16 @@ var ts; // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - return false; + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; } } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { @@ -67227,8 +68153,7 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - oldProgram.structureIsReused = true; - return true; + return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return { @@ -67616,7 +68541,7 @@ var ts; return result; } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { var allDiagnostics = []; @@ -67647,7 +68572,6 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); - var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; var ambientModules; @@ -67694,7 +68618,7 @@ var ts; } break; case 233 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -67705,7 +68629,7 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - if (isDtsFile) { + if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(moduleName.text); } @@ -67734,45 +68658,52 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - var diagnosticArgument; - var diagnostic; + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - diagnosticArgument = [fileName]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + } } + return sourceFile; } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); - if (!nonTsFile) { - if (options.allowNonTsExtensions) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; - } + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + return sourceFileWithAddedExtension; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); - } - } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -67925,11 +68856,11 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -67986,7 +68917,7 @@ var ts; var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!ts.isDeclarationFile(sourceFile)) { + if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); @@ -68084,12 +69015,12 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -69266,57 +70197,37 @@ var ts; * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; + } + if (exclude) { + json.exclude = exclude; + } + if (files) { + json.files = files; + } + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; + } + return options; + })(); + options = ts.extend(existingOptions, options); + options.configFilePath = configFileName; // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - if (include && !json["include"]) { - json["include"] = include; - } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; - } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } - options = ts.extend(existingOptions, options); - options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -69326,39 +70237,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -69389,9 +70268,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { // If no includes were specified, exclude common package folders and the outDir excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; @@ -69409,9 +70285,73 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, // Usually a string. + host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -70046,7 +70986,6 @@ var ts; case 148 /* PropertySignature */: case 261 /* PropertyAssignment */: case 262 /* ShorthandPropertyAssignment */: - case 264 /* EnumMember */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: case 152 /* Constructor */: @@ -70063,9 +71002,11 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 264 /* EnumMember */: case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; + case 232 /* EnumDeclaration */: + return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -70082,7 +71023,7 @@ var ts; case 238 /* ImportDeclaration */: case 243 /* ExportAssignment */: case 244 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; // An external module can be a Value case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; @@ -70241,7 +71182,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -70256,36 +71197,6 @@ var ts; ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - ts.isInsideComment = isInsideComment; function getContainerNode(node) { while (true) { node = node.parent; @@ -70590,78 +71501,53 @@ var ts; * position >= start and (position < end or (position === end && token is keyword or identifier)) */ function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; /* Gets the token whose text has range [start, end) and position >= start * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) */ function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTouchingToken(sourceFile, position, includeJsDocComment, includeItemAtEndPosition) { return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { // exit early return current; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } - } - } - } // find the child that contains 'position' - for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) { - var child = _b[_a]; - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { + for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + if (ts.isJSDocNode(child) && !includeJsDocComment) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } + if (start > position) { + continue; + } + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; } } } @@ -70679,7 +71565,7 @@ var ts; function findTokenOnLeftOfPosition(file, position) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -70788,15 +71674,11 @@ var ts; return false; } ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; /** * returns true if the position is in between the open and close elements of an JSX expression. */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return false; } @@ -70825,18 +71707,32 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + function isInComment(sourceFile, position, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } + return position <= tokenAtPosition.getStart(sourceFile) && + (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || + isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); + function isInCommentRange(commentRanges) { + return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); + } + } + ts.isInComment = isInComment; + function isPositionInCommentRange(_a, position, text) { + var pos = _a.pos, end = _a.end, kind = _a.kind; + if (pos < position && position < end) { + return true; + } + else if (position === end) { // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): // @@ -70847,18 +71743,16 @@ var ts; // /* asdf */^ // // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + return kind === 2 /* SingleLineCommentTrivia */ || + // true for unterminated multi-line comment + !(text.charCodeAt(end - 1) === 47 /* slash */ && text.charCodeAt(end - 2) === 42 /* asterisk */); + } + else { + return false; } - return false; } - ts.isInCommentHelper = isInCommentHelper; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); @@ -70872,7 +71766,7 @@ var ts; * Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); + var node = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (ts.isToken(node)) { switch (node.kind) { case 104 /* VarKeyword */: @@ -70979,6 +71873,9 @@ var ts; } ts.isAccessibilityModifier = isAccessibilityModifier; function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } for (var e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { @@ -71027,25 +71924,27 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); - } + }); } ts.isInNonReferenceComment = isInNonReferenceComment; function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromRange(range) { + return ts.createTextSpanFromBounds(range.pos, range.end); + } + ts.createTextSpanFromRange = createTextSpanFromRange; function isTypeKeyword(kind) { switch (kind) { case 119 /* AnyKeyword */: @@ -71326,8 +72225,8 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; diagnostic.start = diagnostic.start - 1; } var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; @@ -71350,7 +72249,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -71422,7 +72321,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -71431,8 +72330,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72441,8 +73340,8 @@ var ts; continue; } var start = completePrefix.length; - var length_6 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -72491,7 +73390,7 @@ var ts; return ts.deduplicate(nonRelativeModules); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return undefined; } @@ -72733,7 +73632,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; if (requestJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; @@ -72763,14 +73662,16 @@ var ts; sortText: "0", }); } - else { + else if (!hasFilteredClassMemberKeywords) { return undefined; } } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { + if (hasFilteredClassMemberKeywords) { + ts.addRange(entries, classMemberKeywordCompletions); + } + else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -72826,8 +73727,8 @@ var ts; var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { + var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -72917,10 +73818,11 @@ var ts; function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) { var candidates = []; var entries = []; + var uniques = ts.createMap(); typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { var candidate = candidates_3[_i]; - addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker); + addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; @@ -72948,9 +73850,10 @@ var ts; } return undefined; } - function addStringLiteralCompletionsFromType(type, result, typeChecker) { + function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { + if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 16384 /* TypeParameter */) { - type = typeChecker.getApparentType(type); + type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; @@ -72958,16 +73861,20 @@ var ts; if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - addStringLiteralCompletionsFromType(t, result, typeChecker); + addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } else if (type.flags & 32 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, - sortText: "0" - }); + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); + result.push({ + name: name, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } } } function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { @@ -73028,11 +73935,11 @@ var ts; // JsDoc tag includes both "@" and tag-name var requestJsDocTag = false; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); // Completion not allowed inside comments, bail out if this is the case - var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { @@ -73083,7 +73990,7 @@ var ts; } } if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -73112,7 +74019,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -73171,6 +74078,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; + var hasFilteredClassMemberKeywords = false; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -73204,7 +74112,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; @@ -73255,6 +74163,7 @@ var ts; function tryGetGlobalSymbols() { var objectLikeContainer; var namedImportsOrExports; + var classLikeContainer; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); @@ -73264,6 +74173,11 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration + getGetClassLikeCompletionSymbols(classLikeContainer); + return true; + } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { @@ -73437,16 +74351,16 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; - var typeForObject; + var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - // If the object literal is being assigned to something of type 'null | { hello: string }', - // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. - typeForObject = typeChecker.getContextualType(objectLikeContainer); - typeForObject = typeForObject && typeForObject.getNonNullableType(); + var typeForObject = typeChecker.getContextualType(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { @@ -73469,7 +74383,11 @@ var ts; } } if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject); existingMembers = objectLikeContainer.elements; } } @@ -73480,10 +74398,6 @@ var ts; else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -73525,6 +74439,53 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ + function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + // We're looking up possible property names from parent type. + isMemberCompletion = true; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for class elements + hasFilteredClassMemberKeywords = true; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); + var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); + if (baseTypeNode || implementsTypeNodes) { + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; + } + } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + var baseClassTypeToGetPropertiesFrom = void 0; + if (baseTypeNode) { + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); + if (classElementModifierFlags & 32 /* Static */) { + // Use static class to get property symbols from + baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); + } + } + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? + undefined : + ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + // List of property symbols of base type that are not private and already implemented + symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? + typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : + undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + } + } + } /** * Returns the immediate owning object literal or binding pattern of a context token, * on the condition that one exists and that the context implies completion should be given. @@ -73561,6 +74522,44 @@ var ts; } return undefined; } + function isFromClassElementDeclaration(node) { + return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetClassLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 17 /* OpenBraceToken */: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number; | } + case 26 /* CommaToken */: + case 25 /* SemicolonToken */: + // class c { method() { } | } + case 18 /* CloseBraceToken */: + if (ts.isClassLike(location)) { + return location; + } + break; + default: + if (isFromClassElementDeclaration(contextToken) && + (isClassMemberCompletionKeyword(contextToken.kind) || + isClassMemberCompletionKeywordText(contextToken.getText()))) { + return contextToken.parent.parent; + } + } + } + // class c { method() { } | method2() { } } + if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + return location.parent; + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -73673,7 +74672,7 @@ var ts; containingNodeKind === 231 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; + return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 146 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && @@ -73686,13 +74685,17 @@ var ts; return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || containingNodeKind === 240 /* NamespaceImport */; + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + if (isFromClassElementDeclaration(contextToken)) { + return false; + } + // falls through case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: case 89 /* FunctionKeyword */: case 104 /* VarKeyword */: - case 125 /* GetKeyword */: - case 135 /* SetKeyword */: case 91 /* ImportKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: @@ -73700,6 +74703,12 @@ var ts; case 138 /* TypeKeyword */: return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here + if (isClassMemberCompletionKeywordText(contextToken.getText()) && + isFromClassElementDeclaration(contextToken)) { + return false; + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -73742,7 +74751,7 @@ var ts; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { + if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; @@ -73776,7 +74785,7 @@ var ts; continue; } // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { + if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; @@ -73790,12 +74799,55 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ + function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { + var m = existingMembers_2[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 149 /* PropertyDeclaration */ && + m.kind !== 151 /* MethodDeclaration */ && + m.kind !== 153 /* GetAccessor */ && + m.kind !== 154 /* SetAccessor */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (isCurrentlyEditingNode(m)) { + continue; + } + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { + continue; + } + // do not filter it out if the static presence doesnt match + var mIsStatic = ts.hasModifier(m, 32 /* Static */); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); + if ((mIsStatic && !currentElementIsStatic) || + (!mIsStatic && currentElementIsStatic)) { + continue; + } + var existingName = ts.getPropertyNameForPropertyNameNode(m.name); + if (existingName) { + existingMemberNames.set(existingName, true); + } + } + return ts.concatenate(ts.filter(baseSymbols, function (baseProperty) { return isValidProperty(baseProperty, 8 /* Private */); }), ts.filter(implementingTypeSymbols, function (implementingProperty) { return isValidProperty(implementingProperty, 24 /* NonPublicAccessibilityModifier */); })); + function isValidProperty(propertySymbol, inValidModifierFlags) { + return !existingMemberNames.get(propertySymbol.name) && + propertySymbol.getDeclarations() && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); + } + } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. * @@ -73807,7 +74859,7 @@ var ts; for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { + if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253 /* JsxAttribute */) { @@ -73816,6 +74868,9 @@ var ts; } return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); } + function isCurrentlyEditingNode(node) { + return node.getStart() <= position && position <= node.getEnd(); + } } /** * Get the name to be display in completion from a given symbol. @@ -73868,6 +74923,27 @@ var ts; sortText: "0" }); } + function isClassMemberCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 123 /* ConstructorKeyword */: + case 131 /* ReadonlyKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 120 /* AsyncKeyword */: + return true; + } + } + function isClassMemberCompletionKeywordText(text) { + return isClassMemberCompletionKeyword(ts.stringToToken(text)); + } + var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { + return isClassMemberCompletionKeywordText(entry.name); + }); function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -73884,9 +74960,9 @@ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { - function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -73898,8 +74974,8 @@ var ts; kind: ts.HighlightSpanKind.none }; } - function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken); + function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -74693,6 +75769,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74771,11 +75850,42 @@ var ts; } }); } + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var refs = []; + var checker = program.getTypeChecker(); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; + var searchSourceFile = searchModuleSymbol.valueDeclaration; + if (searchSourceFile.kind === 265 /* SourceFile */) { + for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { + var ref = _b[_a]; + if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) { + var ref = _d[_c]; + var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); + if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) { + refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref }); + } + } + } + forEachImport(referencingFile, function (_importDecl, moduleSpecifier) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) { + refs.push({ kind: "import", literal: moduleSpecifier }); + } + }); + } + return refs; + } + FindAllReferences.findModuleReferences = findModuleReferences; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -74799,7 +75909,7 @@ var ts; } /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); @@ -74827,26 +75937,20 @@ var ts; } } }); - if (sourceFile.flags & 65536 /* JavaScriptFile */) { - // Find all 'require()' calls. - sourceFile.forEachChild(function recur(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - action(node, node.arguments[0]); - } - else { - node.forEachChild(recur); - } - }); - } } } function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; - if (decl.kind === 238 /* ImportDeclaration */ || decl.kind === 244 /* ExportDeclaration */) { - return decl; + switch (decl.kind) { + case 181 /* CallExpression */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return decl; + case 248 /* ExternalModuleReference */: + return decl.parent; + default: + ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } - ts.Debug.assert(decl.kind === 248 /* ExternalModuleReference */); - return decl.parent; } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. @@ -74983,12 +76087,13 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + return ts.forEach(symbol.declarations, function (decl) { + if (ts.isExportAssignment(decl)) { + return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + } + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); - ts.Debug.assert(!!name); - return name; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { @@ -75035,12 +76140,13 @@ var ts; return { type: "node", node: node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; - function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position); + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); if (!referencedSymbols || !referencedSymbols.length) { return undefined; } var out = []; + var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. @@ -75051,44 +76157,50 @@ var ts; return out; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; - function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node); + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + // A node in a JSDoc comment can't have an implementation anyway. + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265 /* SourceFile */) { + return undefined; + } + var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options)); + function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { + var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) { + function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -75098,10 +76210,6 @@ var ts; switch (def.type) { case "symbol": { var symbol = def.symbol, node_2 = def.node; - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; @@ -75242,7 +76350,7 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) { + function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } if (node.kind === 265 /* SourceFile */) { return undefined; @@ -75253,6 +76361,7 @@ var ts; return special; } } + var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -75263,13 +76372,60 @@ var ts; // Can't have references to something that we have no symbol for. return undefined; } - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol.declarations || !symbol.declarations.length) { - return undefined; + if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { + return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function isModuleReferenceLocation(node) { + if (node.kind !== 9 /* StringLiteral */) { + return false; + } + switch (node.parent.kind) { + case 233 /* ModuleDeclaration */: + case 248 /* ExternalModuleReference */: + case 238 /* ImportDeclaration */: + case 244 /* ExportDeclaration */: + return true; + case 181 /* CallExpression */: + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + default: + return false; + } + } + function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + ts.Debug.assert(!!symbol.valueDeclaration); + var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + if (reference.kind === "import") { + return { type: "node", node: reference.literal }; + } + else { + return { + type: "span", + fileName: reference.referencingFile.fileName, + textSpan: ts.createTextSpanFromRange(reference.ref), + }; + } + }); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 265 /* 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 233 /* ModuleDeclaration */: + references.push({ type: "node", node: decl.name }); + break; + default: + ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + } + return [{ + definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, + references: references + }]; + } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { @@ -75510,7 +76666,11 @@ var ts; // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + if (container === void 0) { container = sourceFile; } + if (fullStart === void 0) { fullStart = false; } + var start = fullStart ? container.getFullStart() : container.getStart(sourceFile); + var end = container.getEnd(); var positions = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. @@ -75542,16 +76702,12 @@ var ts; var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - continue; - } + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } } @@ -75561,31 +76717,31 @@ var ts; // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node && node.kind) { case 71 /* Identifier */: - return node.getWidth() === searchSymbolName.length; + return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - // For string literals we have two additional chars for the quotes - node.getWidth() === searchSymbolName.length + 2; + node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: - return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length; + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; default: return false; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd()); + // Want fullStart so we can find the symbol in JSDoc comments + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, /*fullStart*/ true); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -75604,15 +76760,13 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - var start = state.findInComments ? container.getFullStart() : container.getStart(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd()); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments || container.jsDoc !== undefined); _i < _a.length; _i++) { + var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { // This wasn't the start of a token. Check to see if it might be a // match in a comment or string if that's what the caller is asking @@ -75738,7 +76892,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76004,10 +77158,10 @@ var ts; } var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { - var position = possiblePositions_4[_i]; - var node = ts.getTouchingWord(sourceFile, position); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); + for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { + var position = possiblePositions_3[_i]; + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; } @@ -76058,13 +77212,13 @@ var ts; if (searchSpaceNode.kind === 265 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); }); } else { var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); } return [{ @@ -76073,7 +77227,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || !ts.isThis(node)) { return; } @@ -76110,10 +77264,10 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd()); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); } return [{ @@ -76121,9 +77275,9 @@ var ts; references: references }]; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { - for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) { - var position = possiblePositions_5[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { + var position = possiblePositions_4[_i]; + var node_7 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); } @@ -76319,20 +77473,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_5 = []; + var result_6 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -76476,7 +77630,7 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -76501,17 +77655,10 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 71 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 242 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 241 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.flags & 8388608 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = typeChecker.getAliasedSymbol(symbol); + if (aliased.declarations) { + symbol = aliased; } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -76530,16 +77677,6 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } - if (ts.isJsxOpeningLikeElement(node.parent)) { - // If there are errors when trying to figure out stateless component function, just return the first declaration - // For example: - // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element; - // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element; - // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element; - // let opt =
; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)]; - } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example @@ -76550,23 +77687,17 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element) { - if (typeChecker.getContextualType(element.parent)) { - var result = []; - var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element); - for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) { - var propertySymbol = propertySymbols_1[_i]; - result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - return result; - } + if (element && typeChecker.getContextualType(element.parent)) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); } return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -76579,13 +77710,13 @@ var ts; return undefined; } if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; + var result_7 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_6; + return result_7; } if (!type.symbol) { return undefined; @@ -76593,6 +77724,28 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node, declaration) { + if (node.kind !== 71 /* Identifier */) { + return false; + } + if (node.parent === declaration) { + return true; + } + switch (declaration.kind) { + case 239 /* ImportClause */: + case 237 /* ImportEqualsDeclaration */: + return true; + case 242 /* ImportSpecifier */: + return declaration.parent.kind === 241 /* NamedImports */; + default: + return false; + } + } function getDefinitionFromSymbol(typeChecker, symbol, node) { var result = []; var declarations = symbol.getDeclarations(); @@ -76663,7 +77816,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -76691,7 +77844,7 @@ var ts; function findReferenceInPosition(refs, pos) { for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { + if (ref.pos <= pos && pos <= ref.end) { return ref; } } @@ -76763,6 +77916,7 @@ var ts; "namespace", "param", "private", + "prop", "property", "public", "requires", @@ -76773,8 +77927,6 @@ var ts; "throws", "type", "typedef", - "property", - "prop", "version" ]; var jsDocTagNameCompletionEntries; @@ -76894,7 +78046,7 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -77257,8 +78409,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_4(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. @@ -77301,17 +78453,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77340,8 +78495,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77379,6 +78535,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77388,8 +78545,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77641,8 +78798,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77731,9 +78888,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77750,7 +78907,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -79128,138 +80285,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression - // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. - // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it - // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; - }; - return TokenRangeAccess; - }()); - Shared.TokenRangeAccess = TokenRangeAccess; + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { + allTokens.push(token); + } var TokenValuesAccess = (function () { - function TokenValuesAccess(tks) { - this.tokens = tks && tks.length ? tks : []; + function TokenValuesAccess(tokens) { + if (tokens === void 0) { tokens = []; } + this.tokens = tokens; } TokenValuesAccess.prototype.GetTokens = function () { return this.tokens; @@ -81588,9 +82640,9 @@ var ts; TokenValuesAccess.prototype.Contains = function (token) { return this.tokens.indexOf(token) >= 0; }; + TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { this.token = token; @@ -81601,18 +82653,14 @@ var ts; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { return tokenValue === this.token; }; + TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { - var result = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - result.push(token); - } - return result; + return allTokens; }; TokenAllAccess.prototype.Contains = function () { return true; @@ -81620,51 +82668,80 @@ var ts; TokenAllAccess.prototype.toString = function () { return "[allTokens]"; }; + TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - Shared.TokenAllAccess = TokenAllAccess; - var TokenRange = (function () { - function TokenRange(tokenAccess) { - this.tokenAccess = tokenAccess; + var TokenAllExceptAccess = (function () { + function TokenAllExceptAccess(except) { + this.except = except; } - TokenRange.FromToken = function (token) { - return new TokenRange(new TokenSingleValueAccess(token)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); - }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); - }; - TokenRange.prototype.GetTokens = function () { - return this.tokenAccess.GetTokens(); - }; - TokenRange.prototype.Contains = function (token) { - return this.tokenAccess.Contains(token); - }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); - }; - return TokenRange; + TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; + return TokenAllExceptAccess; }()); - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */]); - Shared.TokenRange = TokenRange; + var TokenRange; + (function (TokenRange) { + function FromToken(token) { + return new TokenSingleValueAccess(token); + } + TokenRange.FromToken = FromToken; + function FromTokens(tokens) { + return new TokenValuesAccess(tokens); + } + TokenRange.FromTokens = FromTokens; + function FromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (ts.indexOf(except, token) < 0) { + tokens.push(token); + } + } + return new TokenValuesAccess(tokens); + } + TokenRange.FromRange = FromRange; + function AnyExcept(token) { + return new TokenAllExceptAccess(token); + } + TokenRange.AnyExcept = AnyExcept; + TokenRange.Any = new TokenAllAccess(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ + 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ + ]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ + 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ + ]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ + 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ + ]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([ + 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, + 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ + ]); + })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81689,6 +82766,8 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); + var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + this.rulesMap = formatting.RulesMap.create(activeRules); } RulesProvider.prototype.getRuleName = function (rule) { return this.globalRules.getRuleName(rule); @@ -81704,123 +82783,9 @@ var ts; }; RulesProvider.prototype.ensureUpToDate = function (options) { if (!this.options || !ts.compareDataObjects(this.options, options)) { - var activeRules = this.createActiveRules(options); - var rulesMap = formatting.RulesMap.create(activeRules); - this.activeRules = activeRules; - this.rulesMap = rulesMap; this.options = ts.clone(options); } }; - RulesProvider.prototype.createActiveRules = function (options) { - var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterConstructor) { - rules.push(this.globalRules.SpaceAfterConstructor); - } - else { - rules.push(this.globalRules.NoSpaceAfterConstructor); - } - if (options.insertSpaceAfterCommaDelimiter) { - rules.push(this.globalRules.SpaceAfterComma); - } - else { - rules.push(this.globalRules.NoSpaceAfterComma); - } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { - rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); - } - else { - rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); - } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { - rules.push(this.globalRules.SpaceAfterKeywordInControl); - } - else { - rules.push(this.globalRules.NoSpaceAfterKeywordInControl); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { - rules.push(this.globalRules.SpaceAfterOpenParen); - rules.push(this.globalRules.SpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenParen); - rules.push(this.globalRules.NoSpaceBeforeCloseParen); - rules.push(this.globalRules.NoSpaceBetweenParens); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { - rules.push(this.globalRules.SpaceAfterOpenBracket); - rules.push(this.globalRules.SpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBracket); - rules.push(this.globalRules.NoSpaceBeforeCloseBracket); - rules.push(this.globalRules.NoSpaceBetweenBrackets); - } - // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true - // so if the option is undefined, we should treat it as true as well - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { - rules.push(this.globalRules.SpaceAfterOpenBrace); - rules.push(this.globalRules.SpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBrace); - rules.push(this.globalRules.NoSpaceBeforeCloseBrace); - rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { - rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); - } - else { - rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); - rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); - } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { - rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); - } - else { - rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); - rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); - } - if (options.insertSpaceAfterSemicolonInForStatements) { - rules.push(this.globalRules.SpaceAfterSemicolonInFor); - } - else { - rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); - } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { - rules.push(this.globalRules.SpaceBeforeBinaryOperator); - rules.push(this.globalRules.SpaceAfterBinaryOperator); - } - else { - rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); - rules.push(this.globalRules.NoSpaceAfterBinaryOperator); - } - if (options.insertSpaceBeforeFunctionParenthesis) { - rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); - } - else { - rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); - } - if (options.placeOpenBraceOnNewLineForControlBlocks) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); - } - if (options.placeOpenBraceOnNewLineForFunctions) { - rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); - rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); - } - if (options.insertSpaceAfterTypeAssertion) { - rules.push(this.globalRules.SpaceAfterTypeAssertion); - } - else { - rules.push(this.globalRules.NoSpaceAfterTypeAssertion); - } - rules = rules.concat(this.globalRules.LowPriorityCommonRules); - return rules; - }; return RulesProvider; }()); formatting.RulesProvider = RulesProvider; @@ -82074,7 +83039,7 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider - var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRangeHasError; var previousRange; var previousParent; @@ -82171,7 +83136,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -83069,9 +84034,7 @@ var ts; if (node.kind === 20 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) && - node.parent.expression !== node) { + if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { @@ -83385,7 +84348,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { // find first non-whitespace position in the leading trivia of the node var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -83397,7 +84360,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -83474,7 +84437,7 @@ var ts; if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -83665,7 +84628,7 @@ var ts; }()); textChanges.ChangeTracker = ChangeTracker; function getNonformattedText(node, sourceFile, newLine) { - var options = { newLine: newLine, target: sourceFile.languageVersion }; + var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); @@ -83694,27 +84657,8 @@ var ts; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } - var nullTransformationContext = { - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, - getCompilerOptions: ts.notImplemented, - getEmitHost: ts.notImplemented, - getEmitResolver: ts.notImplemented, - hoistFunctionDeclaration: ts.noop, - hoistVariableDeclaration: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop - }; function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited @@ -83759,6 +84703,16 @@ var ts; setEnd(nodes, _this.lastNonTriviaPosition); } }; + this.onBeforeEmitToken = function (node) { + if (node) { + setPos(node, _this.lastNonTriviaPosition); + } + }; + this.onAfterEmitToken = function (node) { + if (node) { + setEnd(node, _this.lastNonTriviaPosition); + } + }; } Writer.prototype.setLastNonTriviaPosition = function (s, force) { if (force || !isTrivia(s)) { @@ -83827,14 +84781,14 @@ var ts; var codefix; (function (codefix) { var codeFixes = []; - function registerCodeFix(action) { - ts.forEach(action.errorCodes, function (error) { + function registerCodeFix(codeFix) { + ts.forEach(codeFix.errorCodes, function (error) { var fixes = codeFixes[error]; if (!fixes) { fixes = []; codeFixes[error] = fixes; } - fixes.push(action); + fixes.push(codeFix); }); } codefix.registerCodeFix = registerCodeFix; @@ -83858,6 +84812,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want + var refactors = ts.createMap(); + function registerRefactor(refactor) { + refactors.set(refactor.name, refactor); + } + refactor_1.registerRefactor = registerRefactor; + function getApplicableRefactors(context) { + var results; + var refactorList = []; + refactors.forEach(function (refactor) { + refactorList.push(refactor); + }); + for (var _i = 0, refactorList_1 = refactorList; _i < refactorList_1.length; _i++) { + var refactor_2 = refactorList_1[_i]; + if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { + return results; + } + if (refactor_2.isApplicable(context)) { + (results || (results = [])).push({ name: refactor_2.name, description: refactor_2.description }); + } + } + return results; + } + refactor_1.getApplicableRefactors = getApplicableRefactors; + function getRefactorCodeActions(context, refactorName) { + var result; + var refactor = refactors.get(refactorName); + if (!refactor) { + return undefined; + } + var codeActions = refactor.getCodeActions(context); + if (codeActions) { + ts.addRange((result || (result = [])), codeActions); + } + return result; + } + refactor_1.getRefactorCodeActions = getRefactorCodeActions; + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -83868,7 +84867,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -83924,7 +84923,8 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code], + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { @@ -83933,7 +84933,7 @@ var ts; // This is the identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } @@ -84014,7 +85014,7 @@ var ts; /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); - var indexSignature = ts.createIndexSignatureDeclaration( + var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -84031,6 +85031,60 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], + getCodeActions: getActionsForCorrectSpelling + }); + function getActionsForCorrectSpelling(context) { + var sourceFile = context.sourceFile; + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 + var checker = context.program.getTypeChecker(); + var suggestion; + if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else { + var meaning = ts.getMeaningFromLocation(node); + suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + } + if (suggestion) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: node.getStart(), length: node.getWidth() }, + newText: suggestion + }], + }], + }]; + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 793064 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 107455 /* Value */; + } + return flags; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84047,7 +85101,7 @@ var ts; var start = context.span.start; // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -84085,7 +85139,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 99 /* ThisKeyword */) { return undefined; } @@ -84133,7 +85187,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 123 /* ConstructorKeyword */) { return undefined; } @@ -84158,7 +85212,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { return undefined; @@ -84198,7 +85252,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } @@ -84225,138 +85279,142 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); // this handles var ["computed"] = 12; if (token.kind === 21 /* OpenBracketToken */) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); } switch (token.kind) { case 71 /* Identifier */: - switch (token.parent.kind) { - case 226 /* VariableDeclaration */: - switch (token.parent.parent.parent.kind) { - case 214 /* ForStatement */: - var forStatement = token.parent.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(token.parent); - } - case 216 /* ForOfStatement */: - var forOfStatement = token.parent.parent.parent; - if (forOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); - } - break; - case 215 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return undefined; - case 260 /* CatchClause */: - var catchClause = token.parent.parent; - var parameter = catchClause.variableDeclaration.getChildren()[0]; - return deleteNode(parameter); - default: - var variableStatement = token.parent.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); - } - else { - return deleteNodeInList(token.parent); - } - } - // TODO: #14885 - // falls through - case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); - } - else { - return deleteNodeInList(token.parent); - } - case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } - // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); - case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; - if (namedImports.elements.length === 1) { - // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); - } - else { - // delete import specifier - return deleteNodeInList(token.parent); - } - // handle case where "import d, * as ns from './file'" - // or "'import {a, b as ns} from './file'" - case 239 /* ImportClause */: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - // import |d,| * as ns from './file' - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); - } - else { - return deleteNode(importClause.name); - } - } - case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { - var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); - } - return deleteRange(namespaceImport); - } - } - break; + return deleteIdentifier(); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: return deleteNode(token.parent); + default: + return deleteDefault(); } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + function deleteIdentifier() { + switch (token.parent.kind) { + case 226 /* VariableDeclaration */: + return deleteVariableDeclaration(token.parent); + case 145 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { + return deleteRange(typeParameters); + } + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); + } + return deleteNodeRange(previousToken, nextToken); + } + else { + return deleteNodeInList(token.parent); + } + case 146 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return deleteNode(token.parent); + } + else { + return deleteNodeInList(token.parent); + } + // handle case where 'import a = A;' + case 237 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); + return deleteNode(importEquals); + case 242 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); + return deleteNode(importSpec); + } + else { + // delete import specifier + return deleteNodeInList(token.parent); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 239 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + // import |d,| * as ns from './file' + var start_4 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + } + else { + return deleteNode(importClause.name); + } + } + case 240 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name === token && !namespaceImport.parent.name) { + var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); + return deleteNode(importDecl); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); + return deleteRange({ pos: startPosition, end: namespaceImport.end }); + } + return deleteRange(namespaceImport); + } + default: + return deleteDefault(); + } } - else { - return undefined; + // token.parent is a variableDeclaration + function deleteVariableDeclaration(varDecl) { + switch (varDecl.parent.parent.kind) { + case 214 /* ForStatement */: + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return deleteNode(forInitializer); + } + else { + return deleteNodeInList(varDecl); + } + case 216 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + case 215 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return deleteNode(variableStatement); + } + else { + return deleteNodeInList(varDecl); + } + } } function deleteNode(n) { return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); @@ -84388,6 +85446,15 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ], + getCodeActions: getImportCodeActions + }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; @@ -84485,400 +85552,393 @@ var ts; }; return ImportCodeActionMap; }()); - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); - return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + function getImportCodeActions(context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = []; + var lastImportDeclaration; + var currentTokenMeaning = ts.getMeaningFromLocation(token); + if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token)); + return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true); + } + var candidateModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + candidateModules.push(otherSourceFile.symbol); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); + } + for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { + var moduleSymbol = candidateModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); } } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (cached) { + return cached; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 238 /* ImportDeclaration */) { + return node; } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); - } - } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } + node = node.parent; } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; } - node = node.parent; + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - return undefined; } - } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); } - return ts.getSymbolId(symbol); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; - } - function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); } else { - return [getCodeActionForNewImport()]; + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var importList = importClause.namedBindings; + var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (!importList || importList.elements.length === 0) { + var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); + return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 238 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); } else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + namespacePrefix = declaration.name.getText(); } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!lastImportDeclaration) { + // insert after any existing imports + for (var i = sourceFile.statements.length - 1; i >= 0; i--) { + var statement = sourceFile.statements[i]; + if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { + lastImportDeclaration = statement; + break; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var changeTracker = createChangeTracker(); + var importClause = isDefault + ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + : isNamespaceImport + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + if (!lastImportDeclaration) { + changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + } + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.fileName; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { + return moduleSymbol.name; } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { return undefined; } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); + if (!relativeName) { + return undefined; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { - return undefined; - } - var relativeFileName; - if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { - // if node_modules folder is in this folder or any of its parent folder, no need to keep it. - relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); - } - else { - relativeFileName = getRelativePath(moduleFileName, sourceDirectory); - } - relativeFileName = ts.removeFileExtension(relativeFileName); - if (ts.endsWith(relativeFileName, "/index")) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } - else { - try { - var moduleDirectory = ts.getDirectoryPath(moduleFileName); - var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); - if (packageJsonContent) { - var mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { - relativeFileName = ts.getDirectoryPath(relativeFileName); - } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; + } } - catch (e) { } } - return relativeFileName; } + return relativeName; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); } } return undefined; } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } } - return fileName; } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; } } - } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); - } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = getRelativePathIfInDirectory(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } } } - }); + function createChangeTracker() { + return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + } + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -84905,7 +85965,7 @@ var ts; // We also want to check if the previous line holds a comment for a node on the next line // if so, we do not want to separate the node from its comment if we can. if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -85010,7 +86070,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85068,7 +86128,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -85124,7 +86184,7 @@ var ts; /*returnType*/ undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethodDeclaration( + return ts.createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } @@ -85147,6 +86207,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -85156,6 +86217,188 @@ var ts; /// /// /// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getCodeActions: getCodeActions, + isApplicable: isApplicable + }; + refactor.registerRefactor(convertFunctionToES6Class); + function isApplicable(context) { + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + return symbol && symbol.flags & 16 /* Function */ && symbol.members && symbol.members.size > 0; + } + function getCodeActions(context) { + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return []; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 228 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 226 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return []; + } + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { + var deleteCallback = deletes_1[_i]; + deleteCallback(); + } + return [{ + description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), + changes: changeTracker.getChanges() + }]; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + // Parent node has already been deleted; do nothing + return; + } + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); + } + else { + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + // all instance members are stored in the "member" array of symbol + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, /*modifiers*/ undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + // all static members are stored in the "exports" array of symbol + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 186 /* FunctionExpression */: + var functionExpression = assignmentBinaryExpression.right; + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + case 187 /* ArrowFunction */: + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 207 /* Block */) { + bodyBlock = arrowFunctionBody; + } + else { + var expression = arrowFunctionBody; + bodyBlock = ts.createBlock([ts.createReturn(expression)]); + } + return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + default: + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + return ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + } + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -85182,11 +86425,15 @@ var ts; /// /// /// +/// /// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; + /* @internal */ + var ruleProvider; function createNode(kind, pos, end, parent) { var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : @@ -85237,6 +86484,7 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + ts.Debug.assert(token !== 1 /* EndOfFileToken */); // Else it would infinitely loop var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -85264,27 +86512,32 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143 /* FirstNode */) { + if (ts.isJSDocTag(this)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + } + else if (this.kind >= 143 /* FirstNode */) { + var children_4 = []; ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; var pos_3 = this.pos; var useJSDocScanner_1 = this.kind >= 283 /* FirstJSDocTagNode */ && this.kind <= 293 /* LastJSDocTagNode */; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, node.pos, useJSDocScanner_1); } - children.push(node); + children_4.push(node); if (!isJSDocTagNode) { pos_3 = node.end; } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); + pos_3 = _this.addSyntheticNodes(children_4, pos_3, nodes.pos, useJSDocScanner_1); } - children.push(_this.createSyntaxList(nodes)); + children_4.push(_this.createSyntaxList(nodes)); pos_3 = nodes.end; }; // jsDocComments need to be the first children @@ -85300,11 +86553,14 @@ var ts; pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); + this.addSyntheticNodes(children_4, pos_3, this.end); } ts.scanner.setText(undefined); + this._children = children_4; + } + else { + this._children = ts.emptyArray; } - this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -85571,13 +86827,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_7 !== undefined) { - return result_7; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_8 = getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -85962,7 +87219,7 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider; + ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -85987,10 +87244,6 @@ var ts; return sourceFile; } function getRuleProvider(options) { - // Ensure rules are initialized and up to date wrt to formatting options - if (!ruleProvider) { - ruleProvider = new ts.formatting.RulesProvider(); - } ruleProvider.ensureUpToDate(options); return ruleProvider; } @@ -86228,7 +87481,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -86283,7 +87536,7 @@ var ts; /// Goto implementation function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -86300,7 +87553,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); + return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); @@ -86333,11 +87586,11 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { @@ -86382,7 +87635,7 @@ var ts; function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { return; } @@ -86476,7 +87729,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); // Ensure that there is a corresponding token to match ours. @@ -86640,8 +87893,7 @@ var ts; var matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!ts.isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInComment(sourceFile, matchPosition)) { continue; } var descriptor = undefined; @@ -86729,11 +87981,35 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } + function getRefactorContext(file, positionOrRange, formatOptions) { + var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; + return { + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + newLineCharacter: host.getNewLine(), + rulesProvider: getRuleProvider(formatOptions), + cancellationToken: cancellationToken + }; + } + function getApplicableRefactors(fileName, positionOrRange) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + } + function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + synchronizeHostData(); + var file = getValidSourceFile(fileName); + return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getApplicableRefactors: getApplicableRefactors, + getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -86859,20 +88135,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = ts.getTextOfPropertyName(node.name); if (name && contextualType) { - var result_8 = []; + var result_9 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_8.push(symbol); + result_9.push(symbol); } }); - return result_8; + return result_9; } if (symbol) { - result_8.push(symbol); - return result_8; + result_9.push(symbol); + return result_9; } } return undefined; @@ -86915,7 +88191,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line @@ -88130,6 +89406,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index f610c4fd273..983b4683a4f 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -40,12 +40,20 @@ var ts; var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; + NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { @@ -325,6 +333,15 @@ var ts; } } ts.zipWith = zipWith; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -529,6 +546,28 @@ var ts; return result; } ts.flatMap = flatMap; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1553,6 +1592,10 @@ var ts; return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -2589,6 +2632,7 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, + Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", message: "Cannot re-export a type when the '--isolatedModules' flag is provided." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2696,7 +2740,7 @@ var ts; This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, - Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, + Call_target_does_not_contain_any_signatures: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Call_target_does_not_contain_any_signatures_2346", message: "Call target does not contain any signatures." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, @@ -2891,6 +2935,14 @@ var ts; Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "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: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." }, Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." }, + Property_0_does_not_exist_on_type_1_Did_you_mean_2: { code: 2551, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", message: "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?" }, + Cannot_find_name_0_Did_you_mean_1: { code: 2552, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_1_2552", message: "Cannot find name '{0}'. Did you mean '{1}'?" }, + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: { code: 2553, category: ts.DiagnosticCategory.Error, key: "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", message: "Computed values are not permitted in an enum with string valued members." }, + Expected_0_arguments_but_got_1: { code: 2554, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_1_2554", message: "Expected {0} arguments, but got {1}." }, + Expected_at_least_0_arguments_but_got_1: { code: 2555, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_1_2555", message: "Expected at least {0} arguments, but got {1}." }, + Expected_0_arguments_but_got_a_minimum_of_1: { code: 2556, category: ts.DiagnosticCategory.Error, key: "Expected_0_arguments_but_got_a_minimum_of_1_2556", message: "Expected {0} arguments, but got a minimum of {1}." }, + Expected_at_least_0_arguments_but_got_a_minimum_of_1: { code: 2557, category: ts.DiagnosticCategory.Error, key: "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", message: "Expected at least {0} arguments, but got a minimum of {1}." }, + Expected_0_type_arguments_but_got_1: { code: 2558, category: ts.DiagnosticCategory.Error, key: "Expected_0_type_arguments_but_got_1_2558", message: "Expected {0} type arguments, but got {1}." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "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: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3186,6 +3238,7 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." }, + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: { code: 6137, category: ts.DiagnosticCategory.Error, key: "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", message: "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'." }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -3231,6 +3284,8 @@ var ts; Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." }, List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." }, Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" }, + Reusing_resolution_of_module_0_to_file_1_from_old_program: { code: 6183, category: ts.DiagnosticCategory.Message, key: "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", message: "Reusing resolution of module '{0}' to file '{1}' from old program." }, + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: { code: 6184, category: ts.DiagnosticCategory.Message, key: "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", message: "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3312,6 +3367,9 @@ var ts; Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." }, Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." }, Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." }, + Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, + Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, + Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." }, Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." }, @@ -3860,9 +3918,10 @@ var ts; } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { - return shebangTriviaRegex.test(text) - ? shebangTriviaRegex.exec(text)[0] - : undefined; + var match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { @@ -5873,49 +5932,28 @@ var ts; if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; - basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - return { - options: {}, - fileNames: [], - typeAcquisition: {}, - raw: json, - errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], - wildcardDirectories: {} - }; - } - var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - var baseCompileOnSave; - if (json["extends"]) { - var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; - if (typeof json["extends"] === "string") { - _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseCompileOnSave = _b[3], baseOptions = _b[4]; + var options = (function () { + var _a = parseConfig(json, host, basePath, configFileName, resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + if (include) { + json.include = include; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + if (exclude) { + json.exclude = exclude; } - if (include && !json["include"]) { - json["include"] = include; + if (files) { + json.files = files; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - if (files && !json["files"]) { - json["files"] = files; - } - options = ts.assign({}, baseOptions, options); - } + return options; + })(); options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - if (baseCompileOnSave && json[ts.compileOnSaveCommandLineOption.name] === undefined) { - compileOnSave = baseCompileOnSave; - } return { options: options, fileNames: fileNames, @@ -5925,37 +5963,7 @@ var ts; wildcardDirectories: wildcardDirectories, compileOnSave: compileOnSave }; - function tryExtendsName(extendedConfig) { - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return; - } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); - return; - } - } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); - return; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); - var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; - var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); - errors.push.apply(errors, result.errors); - var _a = ts.map(["include", "exclude", "files"], function (key) { - if (!json[key] && extendedResult.config[key]) { - return ts.map(extendedResult.config[key], updatePath); - } - }), include = _a[0], exclude = _a[1], files = _a[2]; - return [include, exclude, files, result.compileOnSave, result.options]; - } - function getFileNames(errors) { + function getFileNames() { var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { @@ -5986,9 +5994,6 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); } } - else if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } else { excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; @@ -6005,9 +6010,66 @@ var ts; } return result; } - var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined }; + } + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + var include = json.include, exclude = json.exclude, files = json.files; + var compileOnSave = json.compileOnSave; + if (json.extends) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (base) { + include = include || base.include; + exclude = exclude || base.exclude; + files = files || base.files; + if (compileOnSave === undefined) { + compileOnSave = base.compileOnSave; + } + options = ts.assign({}, base.options, options); + } + } + return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + } + function getExtendedConfig(extended, host, basePath, getCanonicalFileName, resolutionStack, errors) { + if (typeof extended !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + return undefined; + } + extended = ts.normalizeSlashes(extended); + if (!(ts.isRootedDiskPath(extended) || ts.startsWith(extended, "./") || ts.startsWith(extended, "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended)); + return undefined; + } + var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extended)); + return undefined; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var _a = parseConfig(extendedResult.config, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors), include = _a.include, exclude = _a.exclude, files = _a.files, options = _a.options, compileOnSave = _a.compileOnSave; + return { include: ts.map(include, updatePath), exclude: ts.map(exclude, updatePath), files: ts.map(files, updatePath), compileOnSave: compileOnSave, options: options }; + } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return false; @@ -6455,12 +6517,11 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return resolved.path; } - function resolvedModuleFromResolved(_a, isExternalLibraryImport) { - var path = _a.path, extension = _a.extension; - return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; - } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; } function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); @@ -6744,6 +6805,8 @@ var ts; case ts.ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; + default: + ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -6877,12 +6940,18 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) { - if (jsOnly === void 0) { jsOnly = false; } - var containingDirectory = ts.getDirectoryPath(containingFile); + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (!resolvedModule) { + throw new Error("Could not resolve JS module " + moduleName + " starting at " + initialDir + ". Looked in: " + failedLookupLocations.join(", ")); + } + return resolvedModule.resolvedFileName; + } + ts.resolveJavaScriptModule = resolveJavaScriptModule; + function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; @@ -6912,7 +6981,6 @@ var ts; } } } - ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker; function realpath(path, host, traceEnabled) { if (!host.realpath) { return path; @@ -7646,6 +7714,9 @@ var ts; _this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package..."); } _this.execSync(_this.npmPath + " install " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + if (_this.log.isEnabled()) { + _this.log.writeLine("Updated " + TypesRegistryPackageName + " npm package"); + } } catch (e) { if (_this.log.isEnabled()) { diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index c43c59e3b12..3aa813c0a8a 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -1,14 +1,14 @@ ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -21,32 +21,32 @@ interface AnimationEventInit extends EventInit { } interface AssertionOptions { - timeoutSeconds?: number; - rpId?: USVString; allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface ClientData { challenge?: string; + extensions?: WebAuthnExtensions; + hashAlg?: string | Algorithm; origin?: string; rpId?: string; - hashAlg?: string | Algorithm; tokenBinding?: string; - extensions?: WebAuthnExtensions; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface CompositionEventInit extends UIEventInit { @@ -86,13 +86,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -106,15 +99,15 @@ interface DeviceLightEventInit extends EventInit { interface DeviceMotionEventInit extends EventInit { acceleration?: DeviceAccelerationDict; accelerationIncludingGravity?: DeviceAccelerationDict; - rotationRate?: DeviceRotationRateDict; interval?: number; + rotationRate?: DeviceRotationRateDict; } interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; alpha?: number; beta?: number; gamma?: number; - absolute?: boolean; } interface DeviceRotationRateDict { @@ -123,17 +116,24 @@ interface DeviceRotationRateDict { gamma?: number; } +interface DOMRectInit { + height?: any; + width?: any; + x?: any; + y?: any; +} + interface DoubleRange { max?: number; min?: number; } interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; colno?: number; error?: any; + filename?: string; + lineno?: number; + message?: string; } interface EventInit { @@ -143,9 +143,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -158,6 +157,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -170,17 +170,17 @@ interface FocusEventInit extends UIEventInit { interface FocusNavigationEventInit extends EventInit { navigationReason?: string; + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface FocusNavigationOrigin { + originHeight?: number; originLeft?: number; originTop?: number; originWidth?: number; - originHeight?: number; } interface GamepadEventInit extends EventInit { @@ -207,11 +207,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -236,39 +236,153 @@ interface LongRange { min?: number; } +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget; + screenX?: number; + screenY?: number; +} + interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; rpDisplayName?: string; userDisplayName?: string; - accountName?: string; userId?: string; - accountImageUri?: string; } interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; deviceClippingEventRatio?: number; deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; } interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; burstLossLength1?: number; burstLossLength2?: number; burstLossLength3?: number; @@ -280,31 +394,36 @@ interface MSAudioRecvPayload extends MSPayloadBase { fecRecvDistance1?: number; fecRecvDistance2?: number; fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; ratioConcealedSamplesAvg?: number; ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; } interface MSAudioRecvSignal { initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; + recvSignalLevelCh1?: number; renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; } interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; audioFECUsed?: boolean; + samplingRate?: number; sendMutePercent?: number; + signal?: MSAudioSendSignal; } interface MSAudioSendSignal { noiseLevel?: number; - sendSignalLevelCh1?: number; sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; } interface MSConnectivity { @@ -322,8 +441,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -333,12 +452,12 @@ interface MSDelay { interface MSDescription extends RTCStats { connectivity?: MSConnectivity; - transport?: RTCIceProtocol; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; } interface MSFIDOCredentialParameters extends MSCredentialParameters { @@ -346,35 +465,35 @@ interface MSFIDOCredentialParameters extends MSCredentialParameters { authenticators?: AAGUID[]; } -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; turnTcpAllocateFailed?: boolean; turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; udpLocalConnectivityFailed?: boolean; udpNatConnectivityFailed?: boolean; udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSJitter { @@ -384,28 +503,28 @@ interface MSJitter { } interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; } interface MSNetwork extends RTCStats { - jitter?: MSJitter; delay?: MSDelay; + jitter?: MSJitter; packetLoss?: MSPacketLoss; utilization?: MSUtilization; } interface MSNetworkConnectivityInfo { - vpn?: boolean; linkspeed?: number; networkConnectionDetails?: string; + vpn?: boolean; } interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; } @@ -423,13 +542,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -437,241 +556,122 @@ interface MSSignatureParameters { } interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: RTCIceProtocol; - localInterface?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - remoteAddrType?: MSIceAddrType; - iceRole?: RTCIceRole; - rtpRtcpMux?: boolean; allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; } interface MSUtilization { - packets?: number; bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; } interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; resolution?: string; videoBitRateAvg?: number; videoBitRateMax?: number; videoFrameRateAvg?: number; videoPacketLossRate?: number; - durationSeconds?: number; } interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; recvVideoStreamsMax?: number; recvVideoStreamsMin?: number; recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; } interface MSVideoResolutionDistribution { cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; h1080Quality?: number; h1440Quality?: number; h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; } interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: MediaKeyMessageType; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - persistentState?: MediaKeysRequirement; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamEventInit extends EventInit { - stream?: MediaStream; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MessageEventInit extends EventInit { - lastEventId?: string; - channel?: string; - data?: any; - origin?: string; - source?: Window; - ports?: MessagePort[]; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; } interface MsZoomToOptions { + animate?: string; contentX?: number; contentY?: number; + scaleFactor?: number; viewportX?: string; viewportY?: string; - scaleFactor?: number; - animate?: string; } interface MutationObserverInit { - childList?: boolean; + attributeFilter?: string[]; + attributeOldValue?: boolean; attributes?: boolean; characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; characterDataOldValue?: boolean; - attributeFilter?: string[]; + childList?: boolean; + subtree?: boolean; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -680,39 +680,39 @@ interface ObjectURLOptions { interface PaymentCurrencyAmount { currency?: string; - value?: string; currencySystem?: string; + value?: string; } interface PaymentDetails { - total?: PaymentItem; displayItems?: PaymentItem[]; - shippingOptions?: PaymentShippingOption[]; - modifiers?: PaymentDetailsModifier[]; error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; } interface PaymentDetailsModifier { - supportedMethods?: string[]; - total?: PaymentItem; additionalDisplayItems?: PaymentItem[]; data?: any; + supportedMethods?: string[]; + total?: PaymentItem; } interface PaymentItem { - label?: string; amount?: PaymentCurrencyAmount; + label?: string; pending?: boolean; } interface PaymentMethodData { - supportedMethods?: string[]; data?: any; + supportedMethods?: string[]; } interface PaymentOptions { - requestPayerName?: boolean; requestPayerEmail?: boolean; + requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; shippingType?: string; @@ -722,9 +722,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -733,14 +733,14 @@ interface PeriodicWaveConstraints { } interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; pressure?: number; tiltX?: number; tiltY?: number; - pointerType?: string; - isPrimary?: boolean; + width?: number; } interface PopStateEventInit extends EventInit { @@ -749,8 +749,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -760,38 +760,63 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: any; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: any; + status?: number; + statusText?: string; } interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - bundlePolicy?: RTCBundlePolicy; peerIdentity?: string; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCDtlsFingerprint { algorithm?: string; value?: string; } interface RTCDtlsParameters { - role?: RTCDtlsRole; fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; } interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; ipAddress?: string; portNumber?: number; - transport?: string; - candidateType?: RTCStatsIceCandidateType; priority?: number; - addressSourceUrl?: string; + transport?: string; } interface RTCIceCandidateComplete { @@ -799,15 +824,15 @@ interface RTCIceCandidateComplete { interface RTCIceCandidateDictionary { foundation?: string; - priority?: number; ip?: string; - protocol?: RTCIceProtocol; + msMTurnSessionId?: string; port?: number; - type?: RTCIceCandidateType; - tcpType?: RTCIceTcpCandidateType; + priority?: number; + protocol?: RTCIceProtocol; relatedAddress?: string; relatedPort?: number; - msMTurnSessionId?: string; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; } interface RTCIceCandidateInit { @@ -822,19 +847,19 @@ interface RTCIceCandidatePair { } interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: RTCStatsIceCandidatePairState; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; } interface RTCIceGatherOptions { @@ -844,285 +869,260 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - usernameFragment?: string; - password?: string; iceLite?: boolean; + password?: string; + usernameFragment?: string; } interface RTCIceServer { + credential?: string; urls?: any; username?: string; - credential?: string; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; bytesReceived?: number; - packetsLost?: number; - jitter?: number; fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; } interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; audioLevel?: number; echoReturnLoss?: number; echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; } interface RTCOfferOptions { - offerToReceiveVideo?: number; - offerToReceiveAudio?: number; - voiceActivityDetection?: boolean; iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; } interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; bytesSent?: number; - targetBitrate?: number; + packetsSent?: number; roundTripTime?: number; + targetBitrate?: number; } interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - interface RTCRtcpFeedback { - type?: string; parameter?: string; + type?: string; } interface RTCRtcpParameters { - ssrc?: number; cname?: string; - reducedSize?: boolean; mux?: boolean; + reducedSize?: boolean; + ssrc?: number; } interface RTCRtpCapabilities { codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; } interface RTCRtpCodecCapability { - name?: string; - kind?: string; clockRate?: number; - preferredPayloadType?: number; + kind?: string; maxptime?: number; - ptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; svcMultiStreamSupport?: boolean; } interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; clockRate?: number; maxptime?: number; - ptime?: number; + name?: string; numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; } interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; audioLevel?: number; + csrc?: number; + timestamp?: number; } interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - resolutionScale?: number; - framerateScale?: number; - maxFramerate?: number; active?: boolean; - encodingId?: string; + codecPayloadType?: number; dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; ssrcRange?: RTCSsrcRange; } interface RTCRtpFecParameters { - ssrc?: number; mechanism?: string; + ssrc?: number; } interface RTCRtpHeaderExtension { kind?: string; - uri?: string; - preferredId?: number; preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; } interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; encrypt?: boolean; + id?: number; + uri?: string; } interface RTCRtpParameters { - muxId?: string; codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; } interface RTCRtpRtxParameters { ssrc?: number; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; muxId?: string; + payloadType?: number; + ssrc?: number; } interface RTCSessionDescriptionInit { - type?: RTCSdpType; sdp?: string; + type?: RTCSdpType; } interface RTCSrtpKeyParam { keyMethod?: string; keySalt?: string; lifetime?: string; - mkiValue?: number; mkiLength?: number; + mkiValue?: number; } interface RTCSrtpSdesParameters { - tag?: number; cryptoSuite?: string; keyParams?: RTCSrtpKeyParam[]; sessionParams?: string[]; + tag?: number; } interface RTCSsrcRange { - min?: number; max?: number; + min?: number; } interface RTCStats { - timestamp?: number; - type?: RTCStatsType; id?: string; msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; } interface RTCStatsReport { } interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; activeConnection?: boolean; - selectedCandidatePairId?: string; + bytesReceived?: number; + bytesSent?: number; localCertificateId?: string; remoteCertificateId?: string; -} - -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; } interface ScopedCredentialDescriptor { - type?: ScopedCredentialType; id?: any; transports?: Transport[]; + type?: ScopedCredentialType; } interface ScopedCredentialOptions { - timeoutSeconds?: number; - rpId?: USVString; excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; } interface ScopedCredentialParameters { - type?: ScopedCredentialType; algorithm?: string | Algorithm; + type?: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; - origin?: string; lastEventId?: string; - source?: ServiceWorker | MessagePort; + origin?: string; ports?: MessagePort[]; + source?: ServiceWorker | MessagePort; } interface SpeechSynthesisEventInit extends EventInit { - utterance?: SpeechSynthesisUtterance; charIndex?: number; elapsedTime?: number; name?: string; + utterance?: SpeechSynthesisUtterance; } interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; detailURI?: string; + explanationString?: string; + siteName?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -1134,13 +1134,13 @@ interface TrackEventInit extends EventInit { } interface TransitionEventInit extends EventInit { - propertyName?: string; elapsedTime?: number; + propertyName?: string; } interface UIEventInit extends EventInit { - view?: Window; detail?: number; + view?: Window; } interface WebAuthnExtensions { @@ -1149,11 +1149,11 @@ interface WebAuthnExtensions { interface WebGLContextAttributes { failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; - depth?: boolean; - stencil?: boolean; antialias?: boolean; + depth?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -1161,10 +1161,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -1183,19 +1183,6 @@ interface WebKitFileCallback { (evt: Event): void; } -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1211,8 +1198,21 @@ interface AnalyserNode extends AudioNode { declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1222,7 +1222,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -1267,7 +1267,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -1280,7 +1280,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -1295,7 +1295,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -1318,7 +1318,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -1364,7 +1364,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -1373,7 +1373,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -1386,7 +1386,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -1405,7 +1405,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -1421,7 +1421,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -1432,7 +1432,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -1446,7 +1446,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -1469,7 +1469,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -1478,7 +1478,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -1487,13 +1487,13 @@ interface BeforeUnloadEvent extends Event { declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; -} +}; interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; + readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1501,7 +1501,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -1514,16 +1514,305 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + put(request: RequestInfo, response: Response): Promise; } +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): any; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { } +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + interface CSS { supports(property: string, value?: string): boolean; } @@ -1536,7 +1825,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -1545,7 +1834,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1556,7 +1845,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -1567,7 +1856,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -1577,7 +1866,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1590,7 +1879,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -1599,7 +1888,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -1609,7 +1898,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -1621,7 +1910,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -1631,8 +1920,8 @@ interface CSSRule { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1648,8 +1937,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1657,7 +1946,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -1668,13 +1957,13 @@ interface CSSRuleList { declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; -} +}; interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignSelf: string | null; alignmentBaseline: string | null; + alignSelf: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -1750,9 +2039,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; + columns: string | null; columnSpan: string | null; columnWidth: any; - columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -1822,24 +2111,24 @@ interface CSSStyleDeclaration { minHeight: string | null; minWidth: string | null; msContentZoomChaining: string | null; + msContentZooming: string | null; msContentZoomLimit: string | null; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string | null; msContentZoomSnapPoints: string | null; msContentZoomSnapType: string | null; - msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumnSpan: any; msGridColumns: string | null; + msGridColumnSpan: any; msGridRow: any; msGridRowAlign: string | null; - msGridRowSpan: any; msGridRows: string | null; + msGridRowSpan: any; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -1975,9 +2264,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; + webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; - webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2029,7 +2318,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -2040,7 +2329,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -2066,7 +2355,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -2074,296 +2363,7 @@ interface CSSSupportsRule extends CSSConditionRule { declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; -} - -interface Cache { - add(request: RequestInfo): Promise; - addAll(requests: RequestInfo[]): Promise; - delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; - put(request: RequestInfo, response: Response): Promise; -} - -declare var Cache: { - prototype: Cache; - new(): Cache; -} - -interface CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): any; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; -} - -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: CanvasFillRule; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: any, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} +}; interface CustomEvent extends Event { readonly detail: any; @@ -2373,150 +2373,7 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string | undefined; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} +}; interface DataCue extends TextTrackCue { data: ArrayBuffer; @@ -2527,7 +2384,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -2544,7 +2401,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -2557,7 +2414,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -2571,7 +2428,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -2584,7 +2441,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -2593,7 +2450,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -2604,7 +2461,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -2613,7 +2470,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -2626,7 +2483,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -2639,7 +2496,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -2650,7 +2507,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -2745,299 +2602,291 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ + * Gets the object that has the focus when the parent document has focus. + */ readonly activeElement: Element; /** - * Sets or gets the color of all active links in the document. - */ + * Sets or gets the color of all active links in the document. + */ alinkColor: string; /** - * Returns a reference to the collection of elements contained by the object. - */ + * Returns a reference to the collection of elements contained by the object. + */ readonly all: HTMLAllCollection; /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ anchors: HTMLCollectionOf; /** - * Retrieves a collection of all applet objects in the document. - */ + * Retrieves a collection of all applet objects in the document. + */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ bgColor: string; /** - * Specifies the beginning and end of the document body. - */ + * Specifies the beginning and end of the document body. + */ body: HTMLElement; readonly characterSet: string; /** - * Gets or sets the character set used to encode the object. - */ + * Gets or sets the character set used to encode the object. + */ charset: string; /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ readonly compatMode: string; cookie: string; readonly currentScript: HTMLScriptElement | SVGScriptElement; readonly defaultView: Window; /** - * Sets or gets a value that indicates whether the document can be edited. - */ + * Sets or gets a value that indicates whether the document can be edited. + */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. - */ + * Sets or retrieves a value that indicates the reading order of the object. + */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. - */ + * Gets an object representing the document type declaration associated with the current document. + */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. - */ + * Gets a reference to the root node of the document. + */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. - */ + * Sets or gets the security domain of the document. + */ domain: string; /** - * Retrieves a collection of all embed objects in the document. - */ + * Retrieves a collection of all embed objects in the document. + */ embeds: HTMLCollectionOf; /** - * Sets or gets the foreground (text) color of the document. - */ + * Sets or gets the foreground (text) color of the document. + */ fgColor: string; /** - * Retrieves a collection, in source order, of all form objects in the document. - */ + * Retrieves a collection, in source order, of all form objects in the document. + */ forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; readonly hidden: boolean; /** - * Retrieves a collection, in source order, of img objects in the document. - */ + * Retrieves a collection, in source order, of img objects in the document. + */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. - */ + * Gets the implementation object of the current document. + */ readonly implementation: DOMImplementation; /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. - */ + * Gets the date that the page was last modified, if the page supplies one. + */ readonly lastModified: string; /** - * Sets or gets the color of the document links. - */ + * Sets or gets the color of the document links. + */ linkColor: string; /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ links: HTMLCollectionOf; /** - * Contains information about the current URL. - */ + * Contains information about the current URL. + */ readonly location: Location; - msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; /** - * Fires when the user aborts the download. - * @param ev The event. - */ + * Fires when the user aborts the download. + * @param ev The event. + */ onabort: (this: Document, ev: UIEvent) => any; /** - * Fires when the object is set as the active element. - * @param ev The event. - */ + * Fires when the object is set as the active element. + * @param ev The event. + */ onactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ onbeforeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ onbeforedeactivate: (this: Document, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ onblur: (this: Document, ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ oncanplay: (this: Document, ev: Event) => any; oncanplaythrough: (this: Document, ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ onchange: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ onclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ oncontextmenu: (this: Document, ev: PointerEvent) => any; /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ ondblclick: (this: Document, ev: MouseEvent) => any; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ ondeactivate: (this: Document, ev: UIEvent) => any; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ ondrag: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ ondragend: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. - */ + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ ondragenter: (this: Document, ev: DragEvent) => any; - /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. - */ + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ ondragleave: (this: Document, ev: DragEvent) => any; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ ondragover: (this: Document, ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ ondragstart: (this: Document, ev: DragEvent) => any; ondrop: (this: Document, ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ + * Occurs when the duration attribute is updated. + * @param ev The event. + */ ondurationchange: (this: Document, ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ onemptied: (this: Document, ev: Event) => any; /** - * Occurs when the end of playback is reached. - * @param ev The event - */ + * Occurs when the end of playback is reached. + * @param ev The event + */ onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ + * Fires when an error occurs during object loading. + * @param ev The event. + */ onerror: (this: Document, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - * @param ev The event. - */ + * Fires when the object receives focus. + * @param ev The event. + */ onfocus: (this: Document, ev: FocusEvent) => any; onfullscreenchange: (this: Document, ev: Event) => any; onfullscreenerror: (this: Document, ev: Event) => any; oninput: (this: Document, ev: Event) => any; oninvalid: (this: Document, ev: Event) => any; /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ + * Fires when the user presses a key. + * @param ev The keyboard event + */ onkeydown: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ onkeypress: (this: Document, ev: KeyboardEvent) => any; /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ + * Fires when the user releases a key. + * @param ev The keyboard event + */ onkeyup: (this: Document, ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ + * Fires immediately after the browser loads the object. + * @param ev The event. + */ onload: (this: Document, ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ onloadeddata: (this: Document, ev: Event) => any; /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ onloadedmetadata: (this: Document, ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ onloadstart: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ onmousedown: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ onmousemove: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ onmouseout: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ onmouseover: (this: Document, ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ onmouseup: (this: Document, ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ onmousewheel: (this: Document, ev: WheelEvent) => any; onmscontentzoom: (this: Document, ev: UIEvent) => any; onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; @@ -3057,146 +2906,154 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (this: Document, ev: MSPointerEvent) => any; onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** - * Occurs when playback is paused. - * @param ev The event. - */ + * Occurs when playback is paused. + * @param ev The event. + */ onpause: (this: Document, ev: Event) => any; /** - * Occurs when the play method is requested. - * @param ev The event. - */ + * Occurs when the play method is requested. + * @param ev The event. + */ onplay: (this: Document, ev: Event) => any; /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ + * Occurs when the audio or video has started playing. + * @param ev The event. + */ onplaying: (this: Document, ev: Event) => any; onpointerlockchange: (this: Document, ev: Event) => any; onpointerlockerror: (this: Document, ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ onprogress: (this: Document, ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ onratechange: (this: Document, ev: Event) => any; /** - * Fires when the state of the object has changed. - * @param ev The event - */ + * Fires when the state of the object has changed. + * @param ev The event + */ onreadystatechange: (this: Document, ev: Event) => any; /** - * Fires when the user resets a form. - * @param ev The event. - */ + * Fires when the user resets a form. + * @param ev The event. + */ onreset: (this: Document, ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ onscroll: (this: Document, ev: UIEvent) => any; /** - * Occurs when the seek operation ends. - * @param ev The event. - */ + * Occurs when the seek operation ends. + * @param ev The event. + */ onseeked: (this: Document, ev: Event) => any; /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ + * Occurs when the current playback position is moved. + * @param ev The event. + */ onseeking: (this: Document, ev: Event) => any; /** - * Fires when the current selection changes. - * @param ev The event. - */ + * Fires when the current selection changes. + * @param ev The event. + */ onselect: (this: Document, ev: UIEvent) => any; /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ + * Fires when the selection state of a document changes. + * @param ev The event. + */ onselectionchange: (this: Document, ev: Event) => any; onselectstart: (this: Document, ev: Event) => any; /** - * Occurs when the download has stopped. - * @param ev The event. - */ + * Occurs when the download has stopped. + * @param ev The event. + */ onstalled: (this: Document, ev: Event) => any; /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ onstop: (this: Document, ev: Event) => any; onsubmit: (this: Document, ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ onsuspend: (this: Document, ev: Event) => any; /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ + * Occurs to indicate the current playback position. + * @param ev The event. + */ ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ onvolumechange: (this: Document, ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ onwaiting: (this: Document, ev: Event) => any; onwebkitfullscreenchange: (this: Document, ev: Event) => any; onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** - * Retrieves a value that indicates the current state of the object. - */ + * Retrieves a value that indicates the current state of the object. + */ readonly readyState: string; /** - * Gets the URL of the location that referred the user to the current page. - */ + * Gets the URL of the location that referred the user to the current page. + */ readonly referrer: string; /** - * Gets the root svg element in the document hierarchy. - */ + * Gets the root svg element in the document hierarchy. + */ readonly rootElement: SVGSVGElement; /** - * Retrieves a collection of all script objects in the document. - */ + * Retrieves a collection of all script objects in the document. + */ scripts: HTMLCollectionOf; readonly scrollingElement: Element | null; /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; /** - * Contains the title of the document. - */ + * Contains the title of the document. + */ title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ + /** + * Sets or gets the color of the links that the user has visited. + */ vlinkColor: string; readonly webkitCurrentFullScreenElement: Element | null; readonly webkitFullscreenElement: Element | null; @@ -3205,243 +3062,243 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven readonly xmlEncoding: string | null; xmlStandalone: boolean; /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ + * Gets or sets the version attribute specified in the declaration of an XML document. + */ xmlVersion: string | null; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; clear(): void; /** - * Closes an output stream and forces the sent data to display. - */ + * Closes an output stream and forces the sent data to display. + */ close(): void; /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ createComment(data: string): Comment; /** - * Creates a new document. - */ + * Creates a new document. + */ createDocumentFragment(): DocumentFragment; /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list - * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. - */ + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ createRange(): Range; /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ createTextNode(data: string): Text; createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** - * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. - * @param root The root element or node to start traversing on. - * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ focus(): void; /** - * Returns a reference to the first object with the specified value of the ID or NAME attribute. - * @param elementId String that specifies the ID value. Case-insensitive. - */ + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ getElementsByName(elementName: string): NodeListOf; /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ getSelection(): Selection; /** - * Gets a value indicating whether the object currently has focus. - */ + * Gets a value indicating whether the object currently has focus. + */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; msElementsFromPoint(x: number, y: number): NodeListOf; msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @param replace Specifies whether the existing entry for the document is replaced in the history list. - */ + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. - * @param commandId Specifies a command identifier. - */ + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ queryCommandEnabled(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ queryCommandIndeterm(commandId: string): boolean; /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ queryCommandState(commandId: string): boolean; /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ queryCommandSupported(commandId: string): boolean; /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ queryCommandText(commandId: string): string; /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** - * Allows updating the print settings for the page. - */ + * Allows updating the print settings for the page. + */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. - * @param content Specifies the text and HTML tags to write. - */ + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. - * @param content The text and HTML tags to write. - */ + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ writeln(...content: string[]): void; addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3450,7 +3307,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven declare var Document: { prototype: Document; new(): Document; -} +}; interface DocumentFragment extends Node, NodeSelector, ParentNode { getElementById(elementId: string): HTMLElement | null; @@ -3459,7 +3316,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -3473,8 +3330,151 @@ interface DocumentType extends Node, ChildNode { declare var DocumentType: { prototype: DocumentType; new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; } +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DragEvent extends MouseEvent { readonly dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; @@ -3484,7 +3484,7 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; new(): DragEvent; -} +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -3498,27 +3498,7 @@ interface DynamicsCompressorNode extends AudioNode { declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} +}; interface ElementEventMap extends GlobalEventHandlersEventMap { "ariarequest": Event; @@ -3599,9 +3579,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: K): ElementListTagNameMap[K]; @@ -3619,18 +3599,18 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; @@ -3641,9 +3621,9 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec scrollTo(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3652,7 +3632,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -3666,12 +3646,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -3698,7 +3678,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -3709,8 +3689,28 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; +}; + +interface EXT_frag_depth { } +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; @@ -3724,7 +3724,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -3732,7 +3732,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -3743,7 +3743,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -3754,7 +3754,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -3769,7 +3769,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -3779,7 +3779,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -3793,7 +3793,7 @@ interface FocusNavigationEvent extends Event { declare var FocusNavigationEvent: { prototype: FocusNavigationEvent; new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; -} +}; interface FormData { append(name: string, value: string | Blob, fileName?: string): void; @@ -3807,7 +3807,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -3816,7 +3816,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -3831,7 +3831,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -3841,7 +3841,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -3850,7 +3850,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -3861,8 +3861,48 @@ interface Geolocation { declare var Geolocation: { prototype: Geolocation; new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; } +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + interface HTMLAllCollection { readonly length: number; item(nameOrIndex?: string): HTMLCollection | Element | null; @@ -3873,87 +3913,87 @@ interface HTMLAllCollection { declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; -} +}; interface HTMLAnchorElement extends HTMLElement { - Methods: string; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Contains the anchor portion of the URL including the hash sign (#). - */ + * Contains the anchor portion of the URL including the hash sign (#). + */ hash: string; /** - * Contains the hostname and port values of the URL. - */ + * Contains the hostname and port values of the URL. + */ host: string; /** - * Contains the hostname of a URL. - */ + * Contains the hostname of a URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; + Methods: string; readonly mimeType: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; readonly nameProp: string; /** - * Contains the pathname of the URL. - */ + * Contains the pathname of the URL. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Contains the protocol of the URL. - */ + * Contains the protocol of the URL. + */ protocol: string; readonly protocolLong: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; type: string; urn: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -3962,70 +4002,70 @@ interface HTMLAnchorElement extends HTMLElement { declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; -} +}; interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ altHtml: string; /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; border: string; code: string; /** - * Sets or retrieves the URL of the component. - */ + * Sets or retrieves the URL of the component. + */ codeBase: string; /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ + * Sets or retrieves the Internet media type for the code associated with the object. + */ codeType: string; /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ readonly contentDocument: Document; /** - * Sets or retrieves the URL that references the data of the object. - */ + * Sets or retrieves the URL that references the data of the object. + */ data: string; /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ declare: boolean; readonly form: HTMLFormElement; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hspace: number; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ name: string; object: string | null; /** - * Sets or retrieves a message to be displayed while an object is loading. - */ + * Sets or retrieves a message to be displayed while an object is loading. + */ standby: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; vspace: number; width: number; @@ -4036,66 +4076,66 @@ interface HTMLAppletElement extends HTMLElement { declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; -} +}; interface HTMLAreaElement extends HTMLElement { /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Sets or retrieves the coordinates of the object. - */ + * Sets or retrieves the coordinates of the object. + */ coords: string; download: string; /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ hash: string; /** - * Sets or retrieves the hostname and port number of the location or URL. - */ + * Sets or retrieves the hostname and port number of the location or URL. + */ host: string; /** - * Sets or retrieves the host name part of the location or URL. - */ + * Sets or retrieves the host name part of the location or URL. + */ hostname: string; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or gets whether clicks in this region cause action. - */ + * Sets or gets whether clicks in this region cause action. + */ noHref: boolean; /** - * Sets or retrieves the file name or path specified by the object. - */ + * Sets or retrieves the file name or path specified by the object. + */ pathname: string; /** - * Sets or retrieves the port number associated with a URL. - */ + * Sets or retrieves the port number associated with a URL. + */ port: string; /** - * Sets or retrieves the protocol portion of a URL. - */ + * Sets or retrieves the protocol portion of a URL. + */ protocol: string; rel: string; /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ + * Sets or retrieves the substring of the href property that follows the question mark. + */ search: string; /** - * Sets or retrieves the shape of the object. - */ + * Sets or retrieves the shape of the object. + */ shape: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; - /** - * Returns a string representation of an object. - */ + /** + * Returns a string representation of an object. + */ toString(): string; addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4104,7 +4144,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -4112,7 +4152,7 @@ interface HTMLAreasCollection extends HTMLCollectionBase { declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; -} +}; interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4122,30 +4162,16 @@ interface HTMLAudioElement extends HTMLMediaElement { declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} +}; interface HTMLBaseElement extends HTMLElement { /** - * Gets or sets the baseline URL on which relative links are based. - */ + * Gets or sets the baseline URL on which relative links are based. + */ href: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4154,16 +4180,16 @@ interface HTMLBaseElement extends HTMLElement { declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; -} +}; interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; /** - * Sets or retrieves the font size of the object. - */ + * Sets or retrieves the font size of the object. + */ size: number; addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4172,7 +4198,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4231,71 +4257,85 @@ interface HTMLBodyElement extends HTMLElement { declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + interface HTMLButtonElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; - /** - * Sets or retrieves the name of the object. - */ + /** + * Sets or retrieves the name of the object. + */ name: string; status: any; /** - * Gets the classification and default behavior of the button. - */ + * Gets the classification and default behavior of the button. + */ type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; - /** - * Sets or retrieves the default or selected value of the control. - */ + /** + * Sets or retrieves the default or selected value of the control. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4304,32 +4344,32 @@ interface HTMLButtonElement extends HTMLElement { declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; -} +}; interface HTMLCanvasElement extends HTMLElement { /** - * Gets or sets the height of a canvas element on a document. - */ + * Gets or sets the height of a canvas element on a document. + */ height: number; /** - * Gets or sets the width of a canvas element on a document. - */ + * Gets or sets the width of a canvas element on a document. + */ width: number; /** - * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. - * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); - */ + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ msToBlob(): Blob; /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. - */ + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -4339,42 +4379,31 @@ interface HTMLCanvasElement extends HTMLElement { declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; -} +}; interface HTMLCollectionBase { /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Retrieves an object from various collections. - */ + * Retrieves an object from various collections. + */ item(index: number): Element; [index: number]: Element; } interface HTMLCollection extends HTMLCollectionBase { /** - * Retrieves a select object or an object from an options collection. - */ + * Retrieves a select object or an object from an options collection. + */ namedItem(name: string): Element | null; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} +}; interface HTMLDataElement extends HTMLElement { value: string; @@ -4385,7 +4414,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -4396,7 +4425,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -4407,16 +4436,16 @@ interface HTMLDirectoryElement extends HTMLElement { declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; -} +}; interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4425,8 +4454,19 @@ interface HTMLDivElement extends HTMLElement { declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + interface HTMLDocument extends Document { addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4435,7 +4475,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -4608,54 +4648,54 @@ interface HTMLElement extends Element { declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; -} +}; interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; hidden: any; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Retrieves the palette used for the embedded document. - */ + * Retrieves the palette used for the embedded document. + */ readonly palette: string; /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ + * Retrieves the URL of the plug-in used to view an embedded document. + */ readonly pluginspage: string; readonly readyState: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the height and width units of the embed object. - */ + * Sets or retrieves the height and width units of the embed object. + */ units: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4664,39 +4704,39 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; -} +}; interface HTMLFieldSetElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; name: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4705,12 +4745,12 @@ interface HTMLFieldSetElement extends HTMLElement { declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; -} +}; interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** - * Sets or retrieves the current typeface family. - */ + * Sets or retrieves the current typeface family. + */ face: string; addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4719,7 +4759,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -4728,74 +4768,74 @@ interface HTMLFormControlsCollection extends HTMLCollectionBase { declare var HTMLFormControlsCollection: { prototype: HTMLFormControlsCollection; new(): HTMLFormControlsCollection; -} +}; interface HTMLFormElement extends HTMLElement { /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ acceptCharset: string; /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ + * Sets or retrieves the URL to which the form content is sent for processing. + */ action: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Retrieves a collection, in source order, of all controls in a given form. - */ + * Retrieves a collection, in source order, of all controls in a given form. + */ readonly elements: HTMLFormControlsCollection; /** - * Sets or retrieves the MIME encoding for the form. - */ + * Sets or retrieves the MIME encoding for the form. + */ encoding: string; /** - * Sets or retrieves the encoding type for the form. - */ + * Sets or retrieves the encoding type for the form. + */ enctype: string; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ readonly length: number; /** - * Sets or retrieves how to send the form data to the server. - */ + * Sets or retrieves how to send the form data to the server. + */ method: string; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Designates a form that is not validated when submitted. - */ + * Designates a form that is not validated when submitted. + */ noValidate: boolean; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a form object or an object from an elements collection. - */ + * Retrieves a form object or an object from an elements collection. + */ namedItem(name: string): any; /** - * Fires when the user resets a form. - */ + * Fires when the user resets a form. + */ reset(): void; /** - * Fires when a FORM is about to be submitted. - */ + * Fires when a FORM is about to be submitted. + */ submit(): void; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4805,7 +4845,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -4813,68 +4853,68 @@ interface HTMLFrameElementEventMap extends HTMLElementEventMap { interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string | number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLFrameElement, ev: Event) => any; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string | number; addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4883,7 +4923,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4910,33 +4950,33 @@ interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { interface HTMLFrameSetElement extends HTMLElement { border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Sets or retrieves the frame widths of the object. - */ + * Sets or retrieves the frame widths of the object. + */ cols: string; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; name: string; onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** - * Fires when the object loses the input focus. - */ + * Fires when the object loses the input focus. + */ onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** - * Fires when the object receives focus. - */ + * Fires when the object receives focus. + */ onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; onload: (this: HTMLFrameSetElement, ev: Event) => any; @@ -4952,8 +4992,8 @@ interface HTMLFrameSetElement extends HTMLElement { onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** - * Sets or retrieves the frame heights of the object. - */ + * Sets or retrieves the frame heights of the object. + */ rows: string; addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -4962,29 +5002,7 @@ interface HTMLFrameSetElement extends HTMLElement { declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} +}; interface HTMLHeadElement extends HTMLElement { profile: string; @@ -4995,12 +5013,12 @@ interface HTMLHeadElement extends HTMLElement { declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; -} +}; interface HTMLHeadingElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5009,12 +5027,34 @@ interface HTMLHeadingElement extends HTMLElement { declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + interface HTMLHtmlElement extends HTMLElement { /** - * Sets or retrieves the DTD version that governs the current document. - */ + * Sets or retrieves the DTD version that governs the current document. + */ version: string; addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5023,7 +5063,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -5031,79 +5071,79 @@ interface HTMLIFrameElementEventMap extends HTMLElementEventMap { interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; allowFullscreen: boolean; allowPaymentRequest: boolean; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves the document object of the page or frame. - */ + * Retrieves the document object of the page or frame. + */ readonly contentDocument: Document; /** - * Retrieves the object of the specified. - */ + * Retrieves the object of the specified. + */ readonly contentWindow: Window; /** - * Sets or retrieves whether to display a border for the frame. - */ + * Sets or retrieves whether to display a border for the frame. + */ frameBorder: string; /** - * Sets or retrieves the amount of additional space between the frames. - */ + * Sets or retrieves the amount of additional space between the frames. + */ frameSpacing: any; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the horizontal margin for the object. - */ + * Sets or retrieves the horizontal margin for the object. + */ hspace: number; /** - * Sets or retrieves a URI to a long description of the object. - */ + * Sets or retrieves a URI to a long description of the object. + */ longDesc: string; /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ marginHeight: string; /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ marginWidth: string; /** - * Sets or retrieves the frame name. - */ + * Sets or retrieves the frame name. + */ name: string; /** - * Sets or retrieves whether the user can resize the frame. - */ + * Sets or retrieves whether the user can resize the frame. + */ noResize: boolean; /** - * Raised when the object has been completely received from the server. - */ + * Raised when the object has been completely received from the server. + */ onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** - * Sets or retrieves whether the frame can be scrolled. - */ + * Sets or retrieves whether the frame can be scrolled. + */ scrolling: string; /** - * Sets or retrieves a URL to be loaded by the object. - */ + * Sets or retrieves a URL to be loaded by the object. + */ src: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5112,86 +5152,86 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; -} +}; interface HTMLImageElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies the properties of a border drawn around an object. - */ + * Specifies the properties of a border drawn around an object. + */ border: string; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: number; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; /** - * Sets or retrieves whether the image is a server-side image map. - */ + * Sets or retrieves whether the image is a server-side image map. + */ isMap: boolean; /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ longDesc: string; lowsrc: string; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * The original height of the image resource before sizing. - */ + * The original height of the image resource before sizing. + */ readonly naturalHeight: number; /** - * The original width of the image resource before sizing. - */ + * The original width of the image resource before sizing. + */ readonly naturalWidth: number; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: number; readonly x: number; readonly y: number; @@ -5203,210 +5243,210 @@ interface HTMLImageElement extends HTMLElement { declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; -} +}; interface HTMLInputElement extends HTMLElement { /** - * Sets or retrieves a comma-separated list of content types. - */ + * Sets or retrieves a comma-separated list of content types. + */ accept: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a text alternative to the graphic. - */ + * Sets or retrieves a text alternative to the graphic. + */ alt: string; /** - * Specifies whether autocomplete is applied to an editable text field. - */ + * Specifies whether autocomplete is applied to an editable text field. + */ autocomplete: string; /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ checked: boolean; /** - * Retrieves whether the object is fully loaded. - */ + * Retrieves whether the object is fully loaded. + */ readonly complete: boolean; /** - * Sets or retrieves the state of the check box or radio button. - */ + * Sets or retrieves the state of the check box or radio button. + */ defaultChecked: boolean; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Returns a FileList object on a file type input object. - */ + * Returns a FileList object on a file type input object. + */ readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ formAction: string; /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ formEnctype: string; /** - * Overrides the submit method attribute previously specified on a form element. - */ + * Overrides the submit method attribute previously specified on a form element. + */ formMethod: string; /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ formNoValidate: string; /** - * Overrides the target attribute on a form element. - */ + * Overrides the target attribute on a form element. + */ formTarget: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: string; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ hspace: number; indeterminate: boolean; /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ + * Specifies the ID of a pre-defined datalist of options for an input element. + */ readonly list: HTMLElement; /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ max: string; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ min: string; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ + * Gets or sets a string containing a regular expression that the user's input must match. + */ pattern: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; selectionDirection: string; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; size: number; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; status: boolean; /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ step: string; /** - * Returns the content type of the object. - */ + * Returns the content type of the object. + */ type: string; /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ useMap: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Returns the value of the data at the cursor's current position. - */ + * Returns the value of the data at the cursor's current position. + */ value: string; valueAsDate: Date; /** - * Returns the input field value as a number. - */ + * Returns the input field value as a number. + */ valueAsNumber: number; /** - * Sets or retrieves the vertical margin for the object. - */ + * Sets or retrieves the vertical margin for the object. + */ vspace: number; webkitdirectory: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Makes the selection equal to the current object. - */ + * Makes the selection equal to the current object. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start?: number, end?: number, direction?: string): void; /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ stepDown(n?: number): void; /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ stepUp(n?: number): void; addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5415,31 +5455,16 @@ interface HTMLInputElement extends HTMLElement { declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} +}; interface HTMLLabelElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the object to which the given label object is assigned. - */ + * Sets or retrieves the object to which the given label object is assigned. + */ htmlFor: string; addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5448,16 +5473,16 @@ interface HTMLLabelElement extends HTMLElement { declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; -} +}; interface HTMLLegendElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ align: string; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5466,41 +5491,56 @@ interface HTMLLegendElement extends HTMLElement { declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + interface HTMLLinkElement extends HTMLElement, LinkStyle { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; disabled: boolean; /** - * Sets or retrieves a destination URL or an anchor point. - */ + * Sets or retrieves a destination URL or an anchor point. + */ href: string; /** - * Sets or retrieves the language code of the object. - */ + * Sets or retrieves the language code of the object. + */ hreflang: string; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rel: string; /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ + * Sets or retrieves the relationship between the object and the destination of the link. + */ rev: string; /** - * Sets or retrieves the window or frame at which to target content. - */ + * Sets or retrieves the window or frame at which to target content. + */ target: string; /** - * Sets or retrieves the MIME type of the object. - */ + * Sets or retrieves the MIME type of the object. + */ type: string; import?: Document; integrity: string; @@ -5511,16 +5551,16 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; -} +}; interface HTMLMapElement extends HTMLElement { /** - * Retrieves a collection of the area objects defined for the given map object. - */ + * Retrieves a collection of the area objects defined for the given map object. + */ readonly areas: HTMLAreasCollection; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5529,7 +5569,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -5561,7 +5601,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -5570,162 +5610,162 @@ interface HTMLMediaElementEventMap extends HTMLElementEventMap { interface HTMLMediaElement extends HTMLElement { /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ readonly audioTracks: AudioTrackList; /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ + * Gets or sets a value that indicates whether to start playing the media automatically. + */ autoplay: boolean; /** - * Gets a collection of buffered time ranges. - */ + * Gets a collection of buffered time ranges. + */ readonly buffered: TimeRanges; /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ controls: boolean; crossOrigin: string | null; /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ readonly currentSrc: string; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ currentTime: number; defaultMuted: boolean; /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ defaultPlaybackRate: number; /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ readonly duration: number; /** - * Gets information about whether the playback has ended or not. - */ + * Gets information about whether the playback has ended or not. + */ readonly ended: boolean; /** - * Returns an object representing the current error state of the audio or video element. - */ + * Returns an object representing the current error state of the audio or video element. + */ readonly error: MediaError; /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ + * Gets or sets a flag to specify whether playback should restart after it completes. + */ loop: boolean; readonly mediaKeys: MediaKeys | null; /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ msAudioCategory: string; /** - * Specifies the output device id that the audio will be sent to. - */ + * Specifies the output device id that the audio will be sent to. + */ msAudioDeviceType: string; readonly msGraphicsTrustStatus: MSGraphicsTrust; /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ readonly msKeys: MSMediaKeys; /** - * Gets or sets whether the DLNA PlayTo device is available. - */ + * Gets or sets whether the DLNA PlayTo device is available. + */ msPlayToDisabled: boolean; /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ msPlayToPreferredSourceUri: string; /** - * Gets or sets the primary DLNA PlayTo device. - */ + * Gets or sets the primary DLNA PlayTo device. + */ msPlayToPrimary: boolean; /** - * Gets the source associated with the media element for use by the PlayToManager. - */ + * Gets the source associated with the media element for use by the PlayToManager. + */ readonly msPlayToSource: any; /** - * Specifies whether or not to enable low-latency playback on the media element. - */ + * Specifies whether or not to enable low-latency playback on the media element. + */ msRealTime: boolean; /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ muted: boolean; /** - * Gets the current network activity for the element. - */ + * Gets the current network activity for the element. + */ readonly networkState: number; onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** - * Gets a flag that specifies whether playback is paused. - */ + * Gets a flag that specifies whether playback is paused. + */ readonly paused: boolean; /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ playbackRate: number; /** - * Gets TimeRanges for the current media resource that has been played. - */ + * Gets TimeRanges for the current media resource that has been played. + */ readonly played: TimeRanges; /** - * Gets or sets the current playback position, in seconds. - */ + * Gets or sets the current playback position, in seconds. + */ preload: string; readyState: number; /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ readonly seeking: boolean; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcObject: MediaStream | null; readonly textTracks: TextTrackList; readonly videoTracks: VideoTrackList; /** - * Gets or sets the volume level for audio portions of the media element. - */ + * Gets or sets the volume level for audio portions of the media element. + */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** - * Returns a string that specifies whether the client can play a given media resource type. - */ + * Returns a string that specifies whether the client can play a given media resource type. + */ canPlayType(type: string): string; /** - * Resets the audio or video object and loads a new media resource. - */ + * Resets the audio or video object and loads a new media resource. + */ load(): void; /** - * Clears all effects from the media pipeline. - */ + * Clears all effects from the media pipeline. + */ msClearEffects(): void; msGetAsCastingSource(): any; /** - * Inserts the specified audio effect into media pipeline. - */ + * Inserts the specified audio effect into media pipeline. + */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** - * Specifies the media protection manager for a given media pipeline. - */ + * Specifies the media protection manager for a given media pipeline. + */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ pause(): void; /** - * Loads and starts playback of a media resource. - */ - play(): void; + * Loads and starts playback of a media resource. + */ + play(): Promise; setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -5752,7 +5792,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -5764,32 +5804,32 @@ interface HTMLMenuElement extends HTMLElement { declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; -} +}; interface HTMLMetaElement extends HTMLElement { /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ + * Gets or sets meta-information to associate with httpEquiv or name. + */ content: string; /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ httpEquiv: string; /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ + * Sets or retrieves the value specified in the content attribute of the meta object. + */ name: string; /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5798,7 +5838,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -5814,16 +5854,16 @@ interface HTMLMeterElement extends HTMLElement { declare var HTMLMeterElement: { prototype: HTMLMeterElement; new(): HTMLMeterElement; -} +}; interface HTMLModElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; /** - * Sets or retrieves the date and time of a modification to the object. - */ + * Sets or retrieves the date and time of a modification to the object. + */ dateTime: string; addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -5832,13 +5872,130 @@ interface HTMLModElement extends HTMLElement { declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + interface HTMLOListElement extends HTMLElement { compact: boolean; /** - * The starting number. - */ + * The starting number. + */ start: number; type: string; addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -5848,154 +6005,37 @@ interface HTMLOListElement extends HTMLElement { declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} +}; interface HTMLOptGroupElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ readonly text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6004,37 +6044,37 @@ interface HTMLOptGroupElement extends HTMLElement { declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; -} +}; interface HTMLOptionElement extends HTMLElement { /** - * Sets or retrieves the status of an option. - */ + * Sets or retrieves the status of an option. + */ defaultSelected: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the ordinal position of an option in a list box. - */ + * Sets or retrieves the ordinal position of an option in a list box. + */ readonly index: number; /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ label: string; /** - * Sets or retrieves whether the option in the list box is the default item. - */ + * Sets or retrieves whether the option in the list box is the default item. + */ selected: boolean; /** - * Sets or retrieves the text string specified by the option tag. - */ + * Sets or retrieves the text string specified by the option tag. + */ text: string; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6043,7 +6083,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -6055,7 +6095,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -6077,12 +6117,12 @@ interface HTMLOutputElement extends HTMLElement { declare var HTMLOutputElement: { prototype: HTMLOutputElement; new(): HTMLOutputElement; -} +}; interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6092,24 +6132,24 @@ interface HTMLParagraphElement extends HTMLElement { declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; -} +}; interface HTMLParamElement extends HTMLElement { /** - * Sets or retrieves the name of an input parameter for an element. - */ + * Sets or retrieves the name of an input parameter for an element. + */ name: string; /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ + * Sets or retrieves the content type of the resource designated by the value attribute. + */ type: string; /** - * Sets or retrieves the value of an input parameter for an element. - */ + * Sets or retrieves the value of an input parameter for an element. + */ value: string; /** - * Sets or retrieves the data type of the value attribute. - */ + * Sets or retrieves the data type of the value attribute. + */ valueType: string; addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6118,7 +6158,7 @@ interface HTMLParamElement extends HTMLElement { declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; -} +}; interface HTMLPictureElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6128,12 +6168,12 @@ interface HTMLPictureElement extends HTMLElement { declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; -} +}; interface HTMLPreElement extends HTMLElement { /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ width: number; addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6142,24 +6182,24 @@ interface HTMLPreElement extends HTMLElement { declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; -} +}; interface HTMLProgressElement extends HTMLElement { /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Defines the maximum, or "done" value for a progress element. - */ + * Defines the maximum, or "done" value for a progress element. + */ max: number; /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ readonly position: number; /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ value: number; addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6168,12 +6208,12 @@ interface HTMLProgressElement extends HTMLElement { declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; -} +}; interface HTMLQuoteElement extends HTMLElement { /** - * Sets or retrieves reference information about the object. - */ + * Sets or retrieves reference information about the object. + */ cite: string; addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6182,38 +6222,38 @@ interface HTMLQuoteElement extends HTMLElement { declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; -} +}; interface HTMLScriptElement extends HTMLElement { async: boolean; /** - * Sets or retrieves the character set used to encode the object. - */ + * Sets or retrieves the character set used to encode the object. + */ charset: string; crossOrigin: string | null; /** - * Sets or retrieves the status of the script. - */ + * Sets or retrieves the status of the script. + */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. - */ + * Sets or retrieves the event for which the script is written. + */ event: string; - /** - * Sets or retrieves the object that is bound to the event script. - */ + /** + * Sets or retrieves the object that is bound to the event script. + */ htmlFor: string; /** - * Retrieves the URL to an external file that contains the source code or data. - */ + * Retrieves the URL to an external file that contains the source code or data. + */ src: string; /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ + * Sets or retrieves the MIME type for the associated scripting engine. + */ type: string; integrity: string; addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6223,94 +6263,94 @@ interface HTMLScriptElement extends HTMLElement { declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; -} +}; interface HTMLSelectElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the number of objects in a collection. - */ + * Sets or retrieves the number of objects in a collection. + */ length: number; /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ multiple: boolean; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; readonly options: HTMLOptionsCollection; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the index of the selected option in a select object. - */ + * Sets or retrieves the index of the selected option in a select object. + */ selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. - */ + * Sets or retrieves the number of rows in the list box. + */ size: number; /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Adds an element to the areas, controlRange, or options collection. - * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. - */ + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ add(element: HTMLElement, before?: HTMLElement | number): void; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ item(name?: any, index?: any): any; /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ namedItem(name: string): any; /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ remove(index?: number): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6320,18 +6360,18 @@ interface HTMLSelectElement extends HTMLElement { declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; -} +}; interface HTMLSourceElement extends HTMLElement { /** - * Gets or sets the intended media type of the media source. + * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; sizes: string; /** - * The address or URL of the a media resource that is to be considered. - */ + * The address or URL of the a media resource that is to be considered. + */ src: string; srcset: string; /** @@ -6345,7 +6385,7 @@ interface HTMLSourceElement extends HTMLElement { declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; -} +}; interface HTMLSpanElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6355,17 +6395,17 @@ interface HTMLSpanElement extends HTMLElement { declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; -} +}; interface HTMLStyleElement extends HTMLElement, LinkStyle { disabled: boolean; /** - * Sets or retrieves the media type. - */ + * Sets or retrieves the media type. + */ media: string; /** - * Retrieves the CSS language in which the style sheet is written. - */ + * Retrieves the CSS language in which the style sheet is written. + */ type: string; addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6374,16 +6414,16 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; -} +}; interface HTMLTableCaptionElement extends HTMLElement { /** - * Sets or retrieves the alignment of the caption or legend. - */ + * Sets or retrieves the alignment of the caption or legend. + */ align: string; /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ vAlign: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6392,53 +6432,53 @@ interface HTMLTableCaptionElement extends HTMLElement { declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; -} +}; interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves abbreviated text for the object. - */ + * Sets or retrieves abbreviated text for the object. + */ abbr: string; /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ axis: string; bgColor: any; /** - * Retrieves the position of the object in the cells collection of a row. - */ + * Retrieves the position of the object in the cells collection of a row. + */ readonly cellIndex: number; /** - * Sets or retrieves the number columns in the table that the object should span. - */ + * Sets or retrieves the number columns in the table that the object should span. + */ colSpan: number; /** - * Sets or retrieves a list of header cells that provide information for the object. - */ + * Sets or retrieves a list of header cells that provide information for the object. + */ headers: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ + * Sets or retrieves whether the browser automatically performs wordwrap. + */ noWrap: boolean; /** - * Sets or retrieves how many rows in a table the cell should span. - */ + * Sets or retrieves how many rows in a table the cell should span. + */ rowSpan: number; /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6447,20 +6487,20 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; -} +}; interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ + * Sets or retrieves the alignment of the object relative to the display or table. + */ align: string; /** - * Sets or retrieves the number of columns in the group. - */ + * Sets or retrieves the number of columns in the group. + */ span: number; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: any; addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6469,7 +6509,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; -} +}; interface HTMLTableDataCellElement extends HTMLTableCellElement { addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6479,111 +6519,111 @@ interface HTMLTableDataCellElement extends HTMLTableCellElement { declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; -} +}; interface HTMLTableElement extends HTMLElement { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; bgColor: any; /** - * Sets or retrieves the width of the border to draw around the object. - */ + * Sets or retrieves the width of the border to draw around the object. + */ border: string; /** - * Sets or retrieves the border color of the object. - */ + * Sets or retrieves the border color of the object. + */ borderColor: any; /** - * Retrieves the caption object of a table. - */ + * Retrieves the caption object of a table. + */ caption: HTMLTableCaptionElement; /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ cellPadding: string; /** - * Sets or retrieves the amount of space between cells in a table. - */ + * Sets or retrieves the amount of space between cells in a table. + */ cellSpacing: string; /** - * Sets or retrieves the number of columns in the table. - */ + * Sets or retrieves the number of columns in the table. + */ cols: number; /** - * Sets or retrieves the way the border frame around the table is displayed. - */ + * Sets or retrieves the way the border frame around the table is displayed. + */ frame: string; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ rules: string; /** - * Sets or retrieves a description and/or structure of the object. - */ + * Sets or retrieves a description and/or structure of the object. + */ summary: string; /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ tBodies: HTMLCollectionOf; /** - * Retrieves the tFoot object of the table. - */ + * Retrieves the tFoot object of the table. + */ tFoot: HTMLTableSectionElement; /** - * Retrieves the tHead object of the table. - */ + * Retrieves the tHead object of the table. + */ tHead: HTMLTableSectionElement; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ width: string; /** - * Creates an empty caption element in the table. - */ + * Creates an empty caption element in the table. + */ createCaption(): HTMLTableCaptionElement; /** - * Creates an empty tBody element in the table. - */ + * Creates an empty tBody element in the table. + */ createTBody(): HTMLTableSectionElement; /** - * Creates an empty tFoot element in the table. - */ + * Creates an empty tFoot element in the table. + */ createTFoot(): HTMLTableSectionElement; /** - * Returns the tHead element object if successful, or null otherwise. - */ + * Returns the tHead element object if successful, or null otherwise. + */ createTHead(): HTMLTableSectionElement; /** - * Deletes the caption element and its contents from the table. - */ + * Deletes the caption element and its contents from the table. + */ deleteCaption(): void; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Deletes the tFoot element and its contents from the table. - */ + * Deletes the tFoot element and its contents from the table. + */ deleteTFoot(): void; /** - * Deletes the tHead element and its contents from the table. - */ + * Deletes the tHead element and its contents from the table. + */ deleteTHead(): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6592,12 +6632,12 @@ interface HTMLTableElement extends HTMLElement { declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; -} +}; interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ scope: string; addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6606,39 +6646,39 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; -} +}; interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves how the object is aligned with adjacent text. - */ + * Sets or retrieves how the object is aligned with adjacent text. + */ align: string; bgColor: any; /** - * Retrieves a collection of all cells in the table row. - */ + * Retrieves a collection of all cells in the table row. + */ cells: HTMLCollectionOf; /** - * Sets or retrieves the height of the object. - */ + * Sets or retrieves the height of the object. + */ height: any; /** - * Retrieves the position of the object in the rows collection for the table. - */ + * Retrieves the position of the object in the rows collection for the table. + */ readonly rowIndex: number; /** - * Retrieves the position of the object in the collection. - */ + * Retrieves the position of the object in the collection. + */ readonly sectionRowIndex: number; /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ deleteCell(index?: number): void; /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ insertCell(index?: number): HTMLTableDataCellElement; addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6647,26 +6687,26 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; -} +}; interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** - * Sets or retrieves a value that indicates the table alignment. - */ + * Sets or retrieves a value that indicates the table alignment. + */ align: string; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: HTMLCollectionOf; /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ deleteRow(index?: number): void; /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6675,7 +6715,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -6686,105 +6726,105 @@ interface HTMLTemplateElement extends HTMLElement { declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; -} +}; interface HTMLTextAreaElement extends HTMLElement { /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ autofocus: boolean; /** - * Sets or retrieves the width of the object. - */ + * Sets or retrieves the width of the object. + */ cols: number; /** - * Sets or retrieves the initial contents of the object. - */ + * Sets or retrieves the initial contents of the object. + */ defaultValue: string; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. - */ + * Retrieves a reference to the form that the object is embedded in. + */ readonly form: HTMLFormElement; /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ maxLength: number; /** - * Sets or retrieves the name of the object. - */ + * Sets or retrieves the name of the object. + */ name: string; /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ placeholder: string; /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ readOnly: boolean; /** - * When present, marks an element that can't be submitted without a value. - */ + * When present, marks an element that can't be submitted without a value. + */ required: boolean; /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ + * Sets or retrieves the number of horizontal rows contained in the object. + */ rows: number; /** - * Gets or sets the end position or offset of a text selection. - */ + * Gets or sets the end position or offset of a text selection. + */ selectionEnd: number; /** - * Gets or sets the starting position or offset of a text selection. - */ + * Gets or sets the starting position or offset of a text selection. + */ selectionStart: number; /** - * Sets or retrieves the value indicating whether the control is selected. - */ + * Sets or retrieves the value indicating whether the control is selected. + */ status: any; /** - * Retrieves the type of control. - */ + * Retrieves the type of control. + */ readonly type: string; /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ readonly validationMessage: string; /** - * Returns a ValidityState object that represents the validity states of an element. - */ + * Returns a ValidityState object that represents the validity states of an element. + */ readonly validity: ValidityState; /** - * Retrieves or sets the text in the entry field of the textArea element. - */ + * Retrieves or sets the text in the entry field of the textArea element. + */ value: string; /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ readonly willValidate: boolean; /** - * Sets or retrieves how to handle wordwrapping in the object. - */ + * Sets or retrieves how to handle wordwrapping in the object. + */ wrap: string; minLength: number; /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ + * Returns whether a form will validate when it is submitted, without having to submit it. + */ checkValidity(): boolean; /** - * Highlights the input area of a form element. - */ + * Highlights the input area of a form element. + */ select(): void; /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ setCustomValidity(error: string): void; /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ setSelectionRange(start: number, end: number): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6793,7 +6833,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -6804,12 +6844,12 @@ interface HTMLTimeElement extends HTMLElement { declare var HTMLTimeElement: { prototype: HTMLTimeElement; new(): HTMLTimeElement; -} +}; interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. - */ + * Retrieves or sets the text of the object as a string. + */ text: string; addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -6818,7 +6858,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -6843,7 +6883,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -6855,7 +6895,7 @@ interface HTMLUListElement extends HTMLElement { declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; -} +}; interface HTMLUnknownElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; @@ -6865,7 +6905,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -6875,8 +6915,8 @@ interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { interface HTMLVideoElement extends HTMLMediaElement { /** - * Gets or sets the height of the video element. - */ + * Gets or sets the height of the video element. + */ height: number; msHorizontalMirror: boolean; readonly msIsLayoutOptimalForPlayback: boolean; @@ -6888,31 +6928,31 @@ interface HTMLVideoElement extends HTMLMediaElement { onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ poster: string; /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoHeight: number; /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ readonly videoWidth: number; readonly webkitDisplayingFullscreen: boolean; readonly webkitSupportsFullscreen: boolean; /** - * Gets or sets the width of the video element. - */ + * Gets or sets the width of the video element. + */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; + webkitEnterFullScreen(): void; webkitExitFullscreen(): void; + webkitExitFullScreen(): void; addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6920,47 +6960,7 @@ interface HTMLVideoElement extends HTMLMediaElement { declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface History { - readonly length: number; - readonly state: any; - scrollRestoration: ScrollRestoration; - back(): void; - forward(): void; - go(delta?: number): void; - pushState(data: any, title: string, url?: string | null): void; - replaceState(data: any, title: string, url?: string | null): void; -} - -declare var History: { - prototype: History; - new(): History; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -6984,7 +6984,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -6993,7 +6993,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -7010,7 +7010,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7019,7 +7019,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -7030,7 +7030,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -7041,14 +7041,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -7064,7 +7064,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -7080,14 +7080,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -7104,7 +7104,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -7112,7 +7112,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -7126,7 +7126,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -7136,7 +7136,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -7156,7 +7156,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -7166,7 +7166,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -7175,7 +7175,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -7187,7 +7187,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface IntersectionObserver { readonly root: Element | null; @@ -7202,7 +7202,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -7216,7 +7216,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -7251,7 +7251,7 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_NUMPAD: number; readonly DOM_KEY_LOCATION_RIGHT: number; readonly DOM_KEY_LOCATION_STANDARD: number; -} +}; interface ListeningStateChangedEvent extends Event { readonly label: string; @@ -7261,7 +7261,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -7282,7 +7282,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -7292,8 +7292,390 @@ interface LongRunningScriptDetectedEvent extends Event { declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; } +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; @@ -7342,7 +7724,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -7352,7 +7734,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -7362,7 +7744,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -7372,7 +7754,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -7384,7 +7766,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -7395,7 +7777,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -7404,7 +7786,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -7415,7 +7797,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -7451,7 +7833,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -7461,7 +7843,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -7495,7 +7877,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -7521,7 +7903,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -7550,7 +7932,7 @@ declare var MSManipulationEvent: { readonly MS_MANIPULATION_STATE_PRESELECT: number; readonly MS_MANIPULATION_STATE_SELECTING: number; readonly MS_MANIPULATION_STATE_STOPPED: number; -} +}; interface MSMediaKeyError { readonly code: number; @@ -7572,7 +7954,7 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_OUTPUT: number; readonly MS_MEDIA_KEYERR_SERVICE: number; readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} +}; interface MSMediaKeyMessageEvent extends Event { readonly destinationURL: string | null; @@ -7582,7 +7964,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -7591,8 +7973,20 @@ interface MSMediaKeyNeededEvent extends Event { declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -7604,19 +7998,7 @@ interface MSMediaKeySession extends EventTarget { declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} +}; interface MSPointerEvent extends MouseEvent { readonly currentPoint: any; @@ -7639,7 +8021,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -7650,7 +8032,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -7660,7 +8042,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -7671,7 +8053,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -7687,7 +8069,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -7722,7 +8104,7 @@ declare var MSWebViewAsyncOperation: { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; -} +}; interface MSWebViewSettings { isIndexedDBEnabled: boolean; @@ -7732,389 +8114,7 @@ interface MSWebViewSettings { declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: MediaDeviceKind; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevicesEventMap { - "devicechange": Event; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: MediaKeyMessageType; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: Promise; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; - load(sessionId: string): Promise; - remove(): Promise; - update(response: any): Promise; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): Promise; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStreamEventMap { - "active": Event; - "addtrack": MediaStreamTrackEvent; - "inactive": Event; - "removetrack": MediaStreamTrackEvent; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: MediaStream, ev: Event) => any; - onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - oninactive: (this: MediaStream, ev: Event) => any; - onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamEvent extends Event { - readonly stream: MediaStream | null; -} - -declare var MediaStreamEvent: { - prototype: MediaStreamEvent; - new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; -} - -interface MediaStreamTrackEventMap { - "ended": MediaStreamErrorEvent; - "mute": Event; - "overconstrained": MediaStreamErrorEvent; - "unmute": Event; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onmute: (this: MediaStreamTrack, ev: Event) => any; - onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; - onunmute: (this: MediaStreamTrack, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: MediaStreamTrackState; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): Promise; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePortEventMap { - "message": MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, transfer?: any[]): void; - start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} +}; interface MutationEvent extends Event { readonly attrChange: number; @@ -8134,7 +8134,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -8145,7 +8145,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -8162,7 +8162,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -8179,7 +8179,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -8189,7 +8189,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -8198,7 +8198,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -8207,7 +8207,7 @@ interface NavigationEventWithReferrer extends NavigationEvent { declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; -} +}; interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { readonly authentication: WebAuthentication; @@ -8234,7 +8234,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -8309,7 +8309,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -8332,7 +8332,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -8347,7 +8347,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -8358,7 +8358,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -8388,7 +8388,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -8396,7 +8396,7 @@ interface OES_element_index_uint { declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; -} +}; interface OES_standard_derivatives { readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; @@ -8406,7 +8406,7 @@ declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} +}; interface OES_texture_float { } @@ -8414,7 +8414,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -8422,7 +8422,7 @@ interface OES_texture_float_linear { declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; -} +}; interface OES_texture_half_float { readonly HALF_FLOAT_OES: number; @@ -8432,7 +8432,7 @@ declare var OES_texture_half_float: { prototype: OES_texture_half_float; new(): OES_texture_half_float; readonly HALF_FLOAT_OES: number; -} +}; interface OES_texture_half_float_linear { } @@ -8440,7 +8440,7 @@ interface OES_texture_half_float_linear { declare var OES_texture_half_float_linear: { prototype: OES_texture_half_float_linear; new(): OES_texture_half_float_linear; -} +}; interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; @@ -8449,7 +8449,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -8467,7 +8467,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -8488,7 +8488,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -8505,7 +8505,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -8514,7 +8514,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -8533,7 +8533,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -8541,7 +8541,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -8561,7 +8561,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -8583,7 +8583,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; -} +}; interface PaymentRequestUpdateEvent extends Event { updateWith(d: Promise): void; @@ -8592,7 +8592,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -8609,8 +8609,158 @@ interface PaymentResponse { declare var PaymentResponse: { prototype: PaymentResponse; new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; } +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + interface PerfWidgetExternal { readonly activeNetworkRequestCount: number; readonly averageFrameTime: number; @@ -8638,157 +8788,7 @@ interface PerfWidgetExternal { declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: NavigationType; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} +}; interface PeriodicWave { } @@ -8796,7 +8796,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -8806,7 +8806,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -8815,7 +8815,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -8831,7 +8831,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -8844,7 +8844,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -8867,7 +8867,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -8877,7 +8877,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -8887,7 +8887,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -8904,7 +8904,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -8913,7 +8913,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -8925,7 +8925,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -8936,7 +8936,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -8949,7 +8949,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -8959,17 +8959,114 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; } -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + interface RTCDtlsTransportEventMap { "dtlsstatechange": RTCDtlsTransportStateChangedEvent; "error": Event; @@ -8992,7 +9089,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -9001,7 +9098,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -9022,19 +9119,28 @@ interface RTCDtmfSender extends EventTarget { declare var RTCDtmfSender: { prototype: RTCDtmfSender; new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + interface RTCIceCandidate { candidate: string | null; - sdpMLineIndex: number | null; sdpMid: string | null; + sdpMLineIndex: number | null; toJSON(): any; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; -} +}; interface RTCIceCandidatePairChangedEvent extends Event { readonly pair: RTCIceCandidatePair; @@ -9043,7 +9149,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -9064,7 +9170,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -9073,7 +9179,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -9102,7 +9208,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -9111,7 +9217,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -9157,7 +9263,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -9166,7 +9272,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -9190,7 +9296,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -9215,7 +9321,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -9226,7 +9332,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -9243,7 +9349,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -9252,7 +9358,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -9262,112 +9368,421 @@ interface RTCStatsProvider extends EventTarget { declare var RTCStatsProvider: { prototype: RTCStatsProvider; new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; } -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: ExpandGranularity): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; } -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; } -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; - getReader(): ReadableStreamReader; +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStream: { - prototype: ReadableStream; - new(): ReadableStream; +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; } -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise; - releaseLock(): void; +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): any; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } -declare var ReadableStreamReader: { - prototype: ReadableStreamReader; - new(): ReadableStreamReader; +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; } -interface Request extends Object, Body { - readonly cache: RequestCache; - readonly credentials: RequestCredentials; - readonly destination: RequestDestination; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: RequestMode; - readonly redirect: RequestRedirect; - readonly referrer: string; - readonly referrerPolicy: ReferrerPolicy; - readonly type: RequestType; +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): any; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { readonly url: string; - clone(): Request; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; } -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - readonly url: string; - clone(): Response; +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; } -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; } +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9377,7 +9792,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -9401,7 +9816,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -9411,7 +9826,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -9421,7 +9836,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -9431,7 +9846,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -9441,7 +9856,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -9451,7 +9866,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -9461,7 +9876,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -9471,7 +9886,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -9481,7 +9896,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -9491,7 +9906,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -9501,7 +9916,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -9511,7 +9926,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -9521,7 +9936,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9534,7 +9949,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -9545,7 +9960,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -9574,7 +9989,7 @@ declare var SVGComponentTransferFunctionElement: { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} +}; interface SVGDefsElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9584,7 +9999,7 @@ interface SVGDefsElement extends SVGGraphicsElement { declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; -} +}; interface SVGDescElement extends SVGElement { addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9594,7 +10009,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -9632,7 +10047,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -9648,7 +10063,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -9658,7 +10073,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9672,7 +10087,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9719,7 +10134,7 @@ declare var SVGFEBlendElement: { readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} +}; interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9742,7 +10157,7 @@ declare var SVGFEColorMatrixElement: { readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} +}; interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9753,7 +10168,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9784,7 +10199,7 @@ declare var SVGFECompositeElement: { readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} +}; interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly bias: SVGAnimatedNumber; @@ -9814,7 +10229,7 @@ declare var SVGFEConvolveMatrixElement: { readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; -} +}; interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly diffuseConstant: SVGAnimatedNumber; @@ -9829,7 +10244,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9854,7 +10269,7 @@ declare var SVGFEDisplacementMapElement: { readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; -} +}; interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; @@ -9866,7 +10281,7 @@ interface SVGFEDistantLightElement extends SVGElement { declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; -} +}; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9876,7 +10291,7 @@ interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; -} +}; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9886,7 +10301,7 @@ interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; -} +}; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9896,7 +10311,7 @@ interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; -} +}; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9906,7 +10321,7 @@ interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; -} +}; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9916,7 +10331,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9930,7 +10345,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -9941,7 +10356,7 @@ interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; -} +}; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -9951,7 +10366,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -9962,7 +10377,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9982,7 +10397,7 @@ declare var SVGFEMorphologyElement: { readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} +}; interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly dx: SVGAnimatedNumber; @@ -9995,7 +10410,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -10008,7 +10423,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10024,7 +10439,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -10042,7 +10457,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10053,7 +10468,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -10081,7 +10496,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} +}; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly filterResX: SVGAnimatedInteger; @@ -10100,7 +10515,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10114,7 +10529,7 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; -} +}; interface SVGGElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10124,7 +10539,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -10145,7 +10560,7 @@ declare var SVGGradientElement: { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; -} +}; interface SVGGraphicsElement extends SVGElement, SVGTests { readonly farthestViewportElement: SVGElement; @@ -10162,7 +10577,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10177,7 +10592,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -10213,7 +10628,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -10229,21 +10644,7 @@ interface SVGLengthList { declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; -} - -interface SVGLineElement extends SVGGraphicsElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} +}; interface SVGLinearGradientElement extends SVGGradientElement { readonly x1: SVGAnimatedLength; @@ -10257,8 +10658,22 @@ interface SVGLinearGradientElement extends SVGGradientElement { declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -10269,12 +10684,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10282,13 +10697,13 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly height: SVGAnimatedLength; @@ -10304,7 +10719,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -10329,7 +10744,7 @@ interface SVGMatrix { declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; -} +}; interface SVGMetadataElement extends SVGElement { addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10339,7 +10754,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -10348,7 +10763,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -10364,7 +10779,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -10397,7 +10812,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -10447,7 +10862,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -10462,7 +10877,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -10477,7 +10892,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -10485,7 +10900,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -10499,7 +10914,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -10513,7 +10928,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -10525,7 +10940,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -10537,7 +10952,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -10549,7 +10964,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -10561,7 +10976,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -10571,7 +10986,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -10581,7 +10996,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -10591,7 +11006,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -10600,7 +11015,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -10609,7 +11024,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -10619,7 +11034,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -10628,7 +11043,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -10637,7 +11052,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -10653,7 +11068,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -10663,7 +11078,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -10673,7 +11088,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10690,7 +11105,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -10701,7 +11116,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -10717,7 +11132,7 @@ interface SVGPointList { declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; -} +}; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10727,7 +11142,7 @@ interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; -} +}; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10737,7 +11152,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -10775,7 +11190,7 @@ declare var SVGPreserveAspectRatio: { readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} +}; interface SVGRadialGradientElement extends SVGGradientElement { readonly cx: SVGAnimatedLength; @@ -10790,7 +11205,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -10802,7 +11217,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10818,8 +11233,60 @@ interface SVGRectElement extends SVGGraphicsElement { declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + interface SVGSVGElementEventMap extends SVGElementEventMap { "SVGAbort": Event; "SVGError": Event; @@ -10879,59 +11346,7 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement { - readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} +}; interface SVGSwitchElement extends SVGGraphicsElement { addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10941,7 +11356,7 @@ interface SVGSwitchElement extends SVGGraphicsElement { declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; -} +}; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10951,17 +11366,7 @@ interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} +}; interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; @@ -10988,7 +11393,7 @@ declare var SVGTextContentElement: { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; -} +}; interface SVGTextElement extends SVGTextPositioningElement { addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -10998,7 +11403,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -11023,7 +11428,7 @@ declare var SVGTextPathElement: { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} +}; interface SVGTextPositioningElement extends SVGTextContentElement { readonly dx: SVGAnimatedLengthList; @@ -11038,7 +11443,7 @@ interface SVGTextPositioningElement extends SVGTextContentElement { declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; -} +}; interface SVGTitleElement extends SVGElement { addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; @@ -11048,7 +11453,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -11079,7 +11484,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -11097,8 +11502,18 @@ interface SVGTransformList { declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11120,7 +11535,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -11131,7 +11546,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -11141,7 +11556,7 @@ declare var SVGZoomAndPan: { readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} +}; interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -11154,420 +11569,7 @@ interface SVGZoomEvent extends UIEvent { declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; -} - -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -} - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -} - -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: Screen, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNodeEventMap { - "audioprocess": AudioProcessingEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly baseNode: Node; - readonly baseOffset: number; - readonly extentNode: Node; - readonly extentOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - setPosition(parentNode: Node, offset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; -} - -interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; - readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorker: { - prototype: ServiceWorker; - new(): ServiceWorker; -} - -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; -} - -interface ServiceWorkerContainer extends EventTarget { - readonly controller: ServiceWorker | null; - oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; - onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; - readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; - register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerContainer: { - prototype: ServiceWorkerContainer; - new(): ServiceWorkerContainer; -} - -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -} - -interface ServiceWorkerRegistrationEventMap { - "updatefound": Event; -} - -interface ServiceWorkerRegistration extends EventTarget { - readonly active: ServiceWorker | null; - readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; - readonly pushManager: PushManager; - readonly scope: USVString; - readonly sync: SyncManager; - readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; - showNotification(title: string, options?: NotificationOptions): Promise; - unregister(): Promise; - update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ServiceWorkerRegistration: { - prototype: ServiceWorkerRegistration; - new(): ServiceWorkerRegistration; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: AppendMode; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface SpeechSynthesisEventMap { - "voiceschanged": Event; -} - -interface SpeechSynthesis extends EventTarget { - onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; - readonly paused: boolean; - readonly pending: boolean; - readonly speaking: boolean; - cancel(): void; - getVoices(): SpeechSynthesisVoice[]; - pause(): void; - resume(): void; - speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesis: { - prototype: SpeechSynthesis; - new(): SpeechSynthesis; -} - -interface SpeechSynthesisEvent extends Event { - readonly charIndex: number; - readonly elapsedTime: number; - readonly name: string; - readonly utterance: SpeechSynthesisUtterance | null; -} - -declare var SpeechSynthesisEvent: { - prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; -} - -interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; -} - -interface SpeechSynthesisUtterance extends EventTarget { - lang: string; - onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; - onend: (this: SpeechSynthesisUtterance, ev: Event) => any; - onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; - onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; - onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; - onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; - onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; - pitch: number; - rate: number; - text: string; - voice: SpeechSynthesisVoice; - volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SpeechSynthesisUtterance: { - prototype: SpeechSynthesisUtterance; - new(text?: string): SpeechSynthesisUtterance; -} - -interface SpeechSynthesisVoice { - readonly default: boolean; - readonly lang: string; - readonly localService: boolean; - readonly name: string; - readonly voiceURI: string; -} - -declare var SpeechSynthesisVoice: { - prototype: SpeechSynthesisVoice; - new(): SpeechSynthesisVoice; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; - encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; - exportKey(format: "jwk", key: CryptoKey): PromiseLike; - exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; - generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; - unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} +}; interface SyncManager { getTags(): any; @@ -11577,7 +11579,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -11588,7 +11590,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -11620,7 +11622,7 @@ declare var TextEvent: { readonly DOM_INPUT_METHOD_SCRIPT: number; readonly DOM_INPUT_METHOD_UNKNOWN: number; readonly DOM_INPUT_METHOD_VOICE: number; -} +}; interface TextMetrics { readonly width: number; @@ -11629,7 +11631,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -11672,7 +11674,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -11696,7 +11698,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -11708,7 +11710,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -11726,7 +11728,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -11737,7 +11739,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -11753,7 +11755,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -11771,7 +11773,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -11782,7 +11784,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -11791,7 +11793,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -11802,7 +11804,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -11822,7 +11824,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -11833,8 +11835,17 @@ interface UIEvent extends Event { declare var UIEvent: { prototype: UIEvent; new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; } +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + interface URL { hash: string; host: string; @@ -11856,16 +11867,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} +}; interface ValidityState { readonly badInput: boolean; @@ -11883,7 +11885,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -11896,7 +11898,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -11910,7 +11912,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -11934,45 +11936,7 @@ interface VideoTrackList extends EventTarget { declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} +}; interface WaveShaperNode extends AudioNode { curve: Float32Array | null; @@ -11982,7 +11946,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -11992,7 +11956,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -12004,8 +11968,46 @@ interface WebAuthnAssertion { declare var WebAuthnAssertion: { prototype: WebAuthnAssertion; new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; } +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + interface WebGLActiveInfo { readonly name: string; readonly size: number; @@ -12015,7 +12017,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -12023,7 +12025,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -12032,7 +12034,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -12040,7 +12042,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -12048,7 +12050,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -12056,7 +12058,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -12064,7 +12066,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -12325,13 +12327,13 @@ interface WebGLRenderingContext { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12356,9 +12358,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12388,18 +12390,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12433,6 +12435,20 @@ interface WebGLRenderingContext { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12465,23 +12481,9 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12627,13 +12629,13 @@ declare var WebGLRenderingContext: { readonly KEEP: number; readonly LEQUAL: number; readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINEAR: number; readonly LINEAR_MIPMAP_LINEAR: number; readonly LINEAR_MIPMAP_NEAREST: number; readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12658,9 +12660,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; + readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; - readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12690,18 +12692,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB565: number; readonly RGB5_A1: number; + readonly RGB565: number; readonly RGBA: number; readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; readonly SAMPLE_ALPHA_TO_COVERAGE: number; readonly SAMPLE_BUFFERS: number; readonly SAMPLE_COVERAGE: number; readonly SAMPLE_COVERAGE_INVERT: number; readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; readonly SCISSOR_BOX: number; readonly SCISSOR_TEST: number; readonly SHADER_TYPE: number; @@ -12735,6 +12737,20 @@ declare var WebGLRenderingContext: { readonly STREAM_DRAW: number; readonly SUBPIXEL_BITS: number; readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; readonly TEXTURE0: number; readonly TEXTURE1: number; readonly TEXTURE10: number; @@ -12767,23 +12783,9 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; readonly TRIANGLE_FAN: number; readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; readonly UNPACK_ALIGNMENT: number; readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; readonly UNPACK_FLIP_Y_WEBGL: number; @@ -12807,7 +12809,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -12815,7 +12817,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -12826,7 +12828,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -12834,7 +12836,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -12842,7 +12844,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -12882,7 +12884,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -12891,7 +12893,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -12900,7 +12902,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -12913,7 +12915,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -12922,7 +12924,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -12932,7 +12934,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -12942,8 +12944,18 @@ interface WebKitPoint { declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + interface WebSocketEventMap { "close": CloseEvent; "error": Event; @@ -12979,7 +12991,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -13002,7 +13014,7 @@ declare var WheelEvent: { readonly DOM_DELTA_LINE: number; readonly DOM_DELTA_PAGE: number; readonly DOM_DELTA_PIXEL: number; -} +}; interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -13030,6 +13042,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -13088,6 +13101,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "waiting": Event; @@ -13101,8 +13118,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly crypto: Crypto; defaultStatus: string; readonly devicePixelRatio: number; - readonly doNotTrack: string; readonly document: Document; + readonly doNotTrack: string; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13225,9 +13242,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; + readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; - readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13283,7 +13300,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -13300,7 +13317,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLDocument extends Document { addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; @@ -13310,7 +13327,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -13357,7 +13374,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -13367,7 +13384,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -13376,7 +13393,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -13387,7 +13404,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -13396,7 +13413,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -13405,7 +13422,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -13442,7 +13459,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -13458,17 +13475,7 @@ interface XSLTProcessor { declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; -} - -interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new(configuration: RTCConfiguration): webkitRTCPeerConnection; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -13505,6 +13512,81 @@ interface ChildNode { remove(): void; } +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + interface DOML2DeprecatedColorProperty { color: string; } @@ -13513,81 +13595,6 @@ interface DOML2DeprecatedSizeProperty { size: number; } -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"FocusNavigationEvent"): FocusNavigationEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamEvent"): MediaStreamEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; - createEvent(eventInterface:"SpeechSynthesisEvent"): SpeechSynthesisEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - interface ElementTraversal { readonly childElementCount: number; readonly firstElementChild: Element | null; @@ -13632,16 +13639,16 @@ interface GlobalFetch { interface HTMLTableAlignment { /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ ch: string; /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ chOff: string; /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ vAlign: string; } @@ -13866,38 +13873,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface NodeListOf extends NodeList { length: number; @@ -14145,7 +14152,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -14195,8 +14202,50 @@ interface TouchEventInit extends EventModifierInit { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -14204,59 +14253,17 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface VoidFunction { - (): void; +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } -interface RTCPeerConnectionErrorCallback { - (error: DOMError): void; -} interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} -interface IntersectionObserverCallback { - (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +interface VoidFunction { + (): void; } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; @@ -14344,48 +14351,27 @@ interface HTMLElementTagNameMap { "xmp": HTMLPreElement; } -interface ElementTagNameMap { - "a": HTMLAnchorElement; +interface ElementTagNameMap extends HTMLElementTagNameMap { "abbr": HTMLElement; "acronym": HTMLElement; "address": HTMLElement; - "applet": HTMLAppletElement; - "area": HTMLAreaElement; "article": HTMLElement; "aside": HTMLElement; - "audio": HTMLAudioElement; "b": HTMLElement; - "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdo": HTMLElement; "big": HTMLElement; - "blockquote": HTMLQuoteElement; - "body": HTMLBodyElement; - "br": HTMLBRElement; - "button": HTMLButtonElement; - "canvas": HTMLCanvasElement; - "caption": HTMLTableCaptionElement; "center": HTMLElement; "circle": SVGCircleElement; "cite": HTMLElement; "clippath": SVGClipPathElement; "code": HTMLElement; - "col": HTMLTableColElement; - "colgroup": HTMLTableColElement; - "data": HTMLDataElement; - "datalist": HTMLDataListElement; "dd": HTMLElement; "defs": SVGDefsElement; - "del": HTMLModElement; "desc": SVGDescElement; "dfn": HTMLElement; - "dir": HTMLDirectoryElement; - "div": HTMLDivElement; - "dl": HTMLDListElement; "dt": HTMLElement; "ellipse": SVGEllipseElement; "em": HTMLElement; - "embed": HTMLEmbedElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -14410,307 +14396,67 @@ interface ElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; "filter": SVGFilterElement; - "font": HTMLFontElement; "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; - "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "g": SVGGElement; - "h1": HTMLHeadingElement; - "h2": HTMLHeadingElement; - "h3": HTMLHeadingElement; - "h4": HTMLHeadingElement; - "h5": HTMLHeadingElement; - "h6": HTMLHeadingElement; - "head": HTMLHeadElement; "header": HTMLElement; "hgroup": HTMLElement; - "hr": HTMLHRElement; - "html": HTMLHtmlElement; "i": HTMLElement; - "iframe": HTMLIFrameElement; "image": SVGImageElement; - "img": HTMLImageElement; - "input": HTMLInputElement; - "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; "keygen": HTMLElement; - "label": HTMLLabelElement; - "legend": HTMLLegendElement; - "li": HTMLLIElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "link": HTMLLinkElement; - "listing": HTMLPreElement; - "map": HTMLMapElement; "mark": HTMLElement; "marker": SVGMarkerElement; - "marquee": HTMLMarqueeElement; "mask": SVGMaskElement; - "menu": HTMLMenuElement; - "meta": HTMLMetaElement; "metadata": SVGMetadataElement; - "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; "nobr": HTMLElement; "noframes": HTMLElement; "noscript": HTMLElement; - "object": HTMLObjectElement; - "ol": HTMLOListElement; - "optgroup": HTMLOptGroupElement; - "option": HTMLOptionElement; - "output": HTMLOutputElement; - "p": HTMLParagraphElement; - "param": HTMLParamElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "picture": HTMLPictureElement; "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; - "pre": HTMLPreElement; - "progress": HTMLProgressElement; - "q": HTMLQuoteElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; "rt": HTMLElement; "ruby": HTMLElement; "s": HTMLElement; "samp": HTMLElement; - "script": HTMLScriptElement; "section": HTMLElement; - "select": HTMLSelectElement; "small": HTMLElement; - "source": HTMLSourceElement; - "span": HTMLSpanElement; "stop": SVGStopElement; "strike": HTMLElement; "strong": HTMLElement; - "style": HTMLStyleElement; "sub": HTMLElement; "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; - "table": HTMLTableElement; - "tbody": HTMLTableSectionElement; - "td": HTMLTableDataCellElement; - "template": HTMLTemplateElement; "text": SVGTextElement; "textpath": SVGTextPathElement; - "textarea": HTMLTextAreaElement; - "tfoot": HTMLTableSectionElement; - "th": HTMLTableHeaderCellElement; - "thead": HTMLTableSectionElement; - "time": HTMLTimeElement; - "title": HTMLTitleElement; - "tr": HTMLTableRowElement; - "track": HTMLTrackElement; "tspan": SVGTSpanElement; "tt": HTMLElement; "u": HTMLElement; - "ul": HTMLUListElement; "use": SVGUseElement; "var": HTMLElement; - "video": HTMLVideoElement; "view": SVGViewElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; - "xmp": HTMLPreElement; } -interface ElementListTagNameMap { - "a": NodeListOf; - "abbr": NodeListOf; - "acronym": NodeListOf; - "address": NodeListOf; - "applet": NodeListOf; - "area": NodeListOf; - "article": NodeListOf; - "aside": NodeListOf; - "audio": NodeListOf; - "b": NodeListOf; - "base": NodeListOf; - "basefont": NodeListOf; - "bdo": NodeListOf; - "big": NodeListOf; - "blockquote": NodeListOf; - "body": NodeListOf; - "br": NodeListOf; - "button": NodeListOf; - "canvas": NodeListOf; - "caption": NodeListOf; - "center": NodeListOf; - "circle": NodeListOf; - "cite": NodeListOf; - "clippath": NodeListOf; - "code": NodeListOf; - "col": NodeListOf; - "colgroup": NodeListOf; - "data": NodeListOf; - "datalist": NodeListOf; - "dd": NodeListOf; - "defs": NodeListOf; - "del": NodeListOf; - "desc": NodeListOf; - "dfn": NodeListOf; - "dir": NodeListOf; - "div": NodeListOf; - "dl": NodeListOf; - "dt": NodeListOf; - "ellipse": NodeListOf; - "em": NodeListOf; - "embed": NodeListOf; - "feblend": NodeListOf; - "fecolormatrix": NodeListOf; - "fecomponenttransfer": NodeListOf; - "fecomposite": NodeListOf; - "feconvolvematrix": NodeListOf; - "fediffuselighting": NodeListOf; - "fedisplacementmap": NodeListOf; - "fedistantlight": NodeListOf; - "feflood": NodeListOf; - "fefunca": NodeListOf; - "fefuncb": NodeListOf; - "fefuncg": NodeListOf; - "fefuncr": NodeListOf; - "fegaussianblur": NodeListOf; - "feimage": NodeListOf; - "femerge": NodeListOf; - "femergenode": NodeListOf; - "femorphology": NodeListOf; - "feoffset": NodeListOf; - "fepointlight": NodeListOf; - "fespecularlighting": NodeListOf; - "fespotlight": NodeListOf; - "fetile": NodeListOf; - "feturbulence": NodeListOf; - "fieldset": NodeListOf; - "figcaption": NodeListOf; - "figure": NodeListOf; - "filter": NodeListOf; - "font": NodeListOf; - "footer": NodeListOf; - "foreignobject": NodeListOf; - "form": NodeListOf; - "frame": NodeListOf; - "frameset": NodeListOf; - "g": NodeListOf; - "h1": NodeListOf; - "h2": NodeListOf; - "h3": NodeListOf; - "h4": NodeListOf; - "h5": NodeListOf; - "h6": NodeListOf; - "head": NodeListOf; - "header": NodeListOf; - "hgroup": NodeListOf; - "hr": NodeListOf; - "html": NodeListOf; - "i": NodeListOf; - "iframe": NodeListOf; - "image": NodeListOf; - "img": NodeListOf; - "input": NodeListOf; - "ins": NodeListOf; - "isindex": NodeListOf; - "kbd": NodeListOf; - "keygen": NodeListOf; - "label": NodeListOf; - "legend": NodeListOf; - "li": NodeListOf; - "line": NodeListOf; - "lineargradient": NodeListOf; - "link": NodeListOf; - "listing": NodeListOf; - "map": NodeListOf; - "mark": NodeListOf; - "marker": NodeListOf; - "marquee": NodeListOf; - "mask": NodeListOf; - "menu": NodeListOf; - "meta": NodeListOf; - "metadata": NodeListOf; - "meter": NodeListOf; - "nav": NodeListOf; - "nextid": NodeListOf; - "nobr": NodeListOf; - "noframes": NodeListOf; - "noscript": NodeListOf; - "object": NodeListOf; - "ol": NodeListOf; - "optgroup": NodeListOf; - "option": NodeListOf; - "output": NodeListOf; - "p": NodeListOf; - "param": NodeListOf; - "path": NodeListOf; - "pattern": NodeListOf; - "picture": NodeListOf; - "plaintext": NodeListOf; - "polygon": NodeListOf; - "polyline": NodeListOf; - "pre": NodeListOf; - "progress": NodeListOf; - "q": NodeListOf; - "radialgradient": NodeListOf; - "rect": NodeListOf; - "rt": NodeListOf; - "ruby": NodeListOf; - "s": NodeListOf; - "samp": NodeListOf; - "script": NodeListOf; - "section": NodeListOf; - "select": NodeListOf; - "small": NodeListOf; - "source": NodeListOf; - "span": NodeListOf; - "stop": NodeListOf; - "strike": NodeListOf; - "strong": NodeListOf; - "style": NodeListOf; - "sub": NodeListOf; - "sup": NodeListOf; - "svg": NodeListOf; - "switch": NodeListOf; - "symbol": NodeListOf; - "table": NodeListOf; - "tbody": NodeListOf; - "td": NodeListOf; - "template": NodeListOf; - "text": NodeListOf; - "textpath": NodeListOf; - "textarea": NodeListOf; - "tfoot": NodeListOf; - "th": NodeListOf; - "thead": NodeListOf; - "time": NodeListOf; - "title": NodeListOf; - "tr": NodeListOf; - "track": NodeListOf; - "tspan": NodeListOf; - "tt": NodeListOf; - "u": NodeListOf; - "ul": NodeListOf; - "use": NodeListOf; - "var": NodeListOf; - "video": NodeListOf; - "view": NodeListOf; - "wbr": NodeListOf; - "x-ms-webview": NodeListOf; - "xmp": NodeListOf; -} +type ElementListTagNameMap = { + [key in keyof ElementTagNameMap]: NodeListOf +}; -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; @@ -14718,8 +14464,8 @@ declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var doNotTrack: string; declare var document: Document; +declare var doNotTrack: string; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -14842,9 +14588,9 @@ declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; +declare var scrollbars: BarProp; declare var scrollX: number; declare var scrollY: number; -declare var scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -14963,6 +14709,7 @@ type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -14976,6 +14723,12 @@ type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; type MSCredentialType = "FIDO_2_0"; type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; type MSIceType = "failed" | "direct" | "relay"; @@ -14983,12 +14736,6 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; -type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; -type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; -type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; -type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; -type MediaKeysRequirement = "required" | "optional" | "not-allowed"; -type MediaStreamTrackState = "live" | "ended"; type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; @@ -15000,6 +14747,14 @@ type PaymentComplete = "success" | "fail" | ""; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; type RTCDtlsRole = "auto" | "client" | "server"; @@ -15007,9 +14762,9 @@ type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; type RTCIceComponent = "RTP" | "RTCP"; type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; -type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "new" | "gathering" | "complete"; type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceProtocol = "udp" | "tcp"; type RTCIceRole = "controlling" | "controlled"; type RTCIceTcpCandidateType = "active" | "passive" | "so"; @@ -15020,14 +14775,6 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type Transport = "usb" | "nfc" | "ble"; diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 62d6d2d67a7..ba358d6402b 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -1,6 +1,6 @@ ///////////////////////////// -/// IE Worker APIs +/// Worker APIs ///////////////////////////// interface Algorithm { @@ -8,16 +8,16 @@ interface Algorithm { } interface CacheQueryOptions { - ignoreSearch?: boolean; - ignoreMethod?: boolean; - ignoreVary?: boolean; cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; } interface CloseEventInit extends EventInit { - wasClean?: boolean; code?: number; reason?: string; + wasClean?: boolean; } interface EventInit { @@ -49,16 +49,16 @@ interface MessageEventInit extends EventInit { channel?: string; data?: any; origin?: string; - source?: any; ports?: MessagePort[]; + source?: any; } interface NotificationOptions { - dir?: NotificationDirection; - lang?: string; body?: string; - tag?: string; + dir?: NotificationDirection; icon?: string; + lang?: string; + tag?: string; } interface ObjectURLOptions { @@ -66,29 +66,29 @@ interface ObjectURLOptions { } interface PushSubscriptionOptionsInit { - userVisibleOnly?: boolean; applicationServerKey?: any; + userVisibleOnly?: boolean; } interface RequestInit { - method?: string; - headers?: any; body?: any; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; cache?: RequestCache; - redirect?: RequestRedirect; + credentials?: RequestCredentials; + headers?: any; integrity?: string; keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; window?: any; } interface ResponseInit { + headers?: any; status?: number; statusText?: string; - headers?: any; } interface ClientQueryOptions { @@ -156,7 +156,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface Blob { readonly size: number; @@ -169,7 +169,7 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} +}; interface Cache { add(request: RequestInfo): Promise; @@ -184,7 +184,7 @@ interface Cache { declare var Cache: { prototype: Cache; new(): Cache; -} +}; interface CacheStorage { delete(cacheName: string): Promise; @@ -197,7 +197,7 @@ interface CacheStorage { declare var CacheStorage: { prototype: CacheStorage; new(): CacheStorage; -} +}; interface CloseEvent extends Event { readonly code: number; @@ -209,7 +209,7 @@ interface CloseEvent extends Event { declare var CloseEvent: { prototype: CloseEvent; new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; -} +}; interface Console { assert(test?: boolean, message?: string, ...optionalParams: any[]): void; @@ -220,8 +220,8 @@ interface Console { dirxml(value: any): void; error(message?: any, ...optionalParams: any[]): void; exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; groupEnd(): void; info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; @@ -239,7 +239,7 @@ interface Console { declare var Console: { prototype: Console; new(): Console; -} +}; interface Coordinates { readonly accuracy: number; @@ -254,7 +254,7 @@ interface Coordinates { declare var Coordinates: { prototype: Coordinates; new(): Coordinates; -} +}; interface CryptoKey { readonly algorithm: KeyAlgorithm; @@ -266,7 +266,7 @@ interface CryptoKey { declare var CryptoKey: { prototype: CryptoKey; new(): CryptoKey; -} +}; interface DOMError { readonly name: string; @@ -276,7 +276,7 @@ interface DOMError { declare var DOMError: { prototype: DOMError; new(): DOMError; -} +}; interface DOMException { readonly code: number; @@ -296,10 +296,10 @@ interface DOMException { readonly INVALID_STATE_ERR: number; readonly NAMESPACE_ERR: number; readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; readonly NO_DATA_ALLOWED_ERR: number; readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -328,10 +328,10 @@ declare var DOMException: { readonly INVALID_STATE_ERR: number; readonly NAMESPACE_ERR: number; readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; readonly NO_DATA_ALLOWED_ERR: number; readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -342,7 +342,7 @@ declare var DOMException: { readonly URL_MISMATCH_ERR: number; readonly VALIDATION_ERR: number; readonly WRONG_DOCUMENT_ERR: number; -} +}; interface DOMStringList { readonly length: number; @@ -354,7 +354,7 @@ interface DOMStringList { declare var DOMStringList: { prototype: DOMStringList; new(): DOMStringList; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -368,12 +368,12 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; -} +}; interface Event { readonly bubbles: boolean; - cancelBubble: boolean; readonly cancelable: boolean; + cancelBubble: boolean; readonly currentTarget: EventTarget; readonly defaultPrevented: boolean; readonly eventPhase: number; @@ -400,7 +400,7 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; -} +}; interface EventTarget { addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -411,7 +411,7 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -422,7 +422,7 @@ interface File extends Blob { declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} +}; interface FileList { readonly length: number; @@ -433,7 +433,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -448,8 +448,17 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; +}; + +interface FormData { + append(name: string, value: string | Blob, fileName?: string): void; } +declare var FormData: { + prototype: FormData; + new(): FormData; +}; + interface Headers { append(name: string, value: string): void; delete(name: string): void; @@ -462,7 +471,7 @@ interface Headers { declare var Headers: { prototype: Headers; new(init?: any): Headers; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -486,7 +495,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -495,7 +504,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -512,7 +521,7 @@ interface IDBDatabase extends EventTarget { close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -521,7 +530,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -532,7 +541,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -543,14 +552,14 @@ interface IDBIndex { count(key?: IDBKeyRange | IDBValidKey): IDBRequest; get(key: IDBKeyRange | IDBValidKey): IDBRequest; getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; -} +}; interface IDBKeyRange { readonly lower: any; @@ -566,7 +575,7 @@ declare var IDBKeyRange: { lowerBound(lower: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(upper: any, open?: boolean): IDBKeyRange; -} +}; interface IDBObjectStore { readonly indexNames: DOMStringList; @@ -582,14 +591,14 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; -} +}; interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "blocked": Event; @@ -606,7 +615,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -614,7 +623,7 @@ interface IDBRequestEventMap { } interface IDBRequest extends EventTarget { - readonly error: DOMError; + readonly error: DOMException; onerror: (this: IDBRequest, ev: Event) => any; onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: IDBRequestReadyState; @@ -628,7 +637,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -638,7 +647,7 @@ interface IDBTransactionEventMap { interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; - readonly error: DOMError; + readonly error: DOMException; readonly mode: IDBTransactionMode; onabort: (this: IDBTransaction, ev: Event) => any; oncomplete: (this: IDBTransaction, ev: Event) => any; @@ -658,7 +667,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -668,7 +677,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -680,7 +689,7 @@ declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} +}; interface MessageChannel { readonly port1: MessagePort; @@ -690,7 +699,7 @@ interface MessageChannel { declare var MessageChannel: { prototype: MessageChannel; new(): MessageChannel; -} +}; interface MessageEvent extends Event { readonly data: any; @@ -703,7 +712,7 @@ interface MessageEvent extends Event { declare var MessageEvent: { prototype: MessageEvent; new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} +}; interface MessagePortEventMap { "message": MessageEvent; @@ -721,7 +730,7 @@ interface MessagePort extends EventTarget { declare var MessagePort: { prototype: MessagePort; new(): MessagePort; -} +}; interface NotificationEventMap { "click": Event; @@ -751,7 +760,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface Performance { readonly navigation: PerformanceNavigation; @@ -774,7 +783,7 @@ interface Performance { declare var Performance: { prototype: Performance; new(): Performance; -} +}; interface PerformanceNavigation { readonly redirectCount: number; @@ -793,18 +802,18 @@ declare var PerformanceNavigation: { readonly TYPE_NAVIGATE: number; readonly TYPE_RELOAD: number; readonly TYPE_RESERVED: number; -} +}; interface PerformanceTiming { readonly connectEnd: number; readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -824,7 +833,7 @@ interface PerformanceTiming { declare var PerformanceTiming: { prototype: PerformanceTiming; new(): PerformanceTiming; -} +}; interface Position { readonly coords: Coordinates; @@ -834,7 +843,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -851,7 +860,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -863,7 +872,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -874,7 +883,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -887,7 +896,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -897,7 +906,7 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; -} +}; interface ReadableStream { readonly locked: boolean; @@ -908,7 +917,7 @@ interface ReadableStream { declare var ReadableStream: { prototype: ReadableStream; new(): ReadableStream; -} +}; interface ReadableStreamReader { cancel(): Promise; @@ -919,7 +928,7 @@ interface ReadableStreamReader { declare var ReadableStreamReader: { prototype: ReadableStreamReader; new(): ReadableStreamReader; -} +}; interface Request extends Object, Body { readonly cache: RequestCache; @@ -941,7 +950,7 @@ interface Request extends Object, Body { declare var Request: { prototype: Request; new(input: Request | string, init?: RequestInit): Request; -} +}; interface Response extends Object, Body { readonly body: ReadableStream | null; @@ -957,7 +966,9 @@ interface Response extends Object, Body { declare var Response: { prototype: Response; new(body?: any, init?: ResponseInit): Response; -} + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; interface ServiceWorkerEventMap extends AbstractWorkerEventMap { "statechange": Event; @@ -975,7 +986,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker { declare var ServiceWorker: { prototype: ServiceWorker; new(): ServiceWorker; -} +}; interface ServiceWorkerRegistrationEventMap { "updatefound": Event; @@ -1000,7 +1011,7 @@ interface ServiceWorkerRegistration extends EventTarget { declare var ServiceWorkerRegistration: { prototype: ServiceWorkerRegistration; new(): ServiceWorkerRegistration; -} +}; interface SyncManager { getTags(): any; @@ -1010,7 +1021,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface URL { hash: string; @@ -1033,7 +1044,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} +}; interface WebSocketEventMap { "close": CloseEvent; @@ -1070,7 +1081,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -1087,7 +1098,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -1133,7 +1144,7 @@ declare var XMLHttpRequest: { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; -} +}; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; @@ -1143,7 +1154,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -1258,7 +1269,7 @@ interface Client { declare var Client: { prototype: Client; new(): Client; -} +}; interface Clients { claim(): Promise; @@ -1270,7 +1281,7 @@ interface Clients { declare var Clients: { prototype: Clients; new(): Clients; -} +}; interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "message": MessageEvent; @@ -1287,7 +1298,7 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { declare var DedicatedWorkerGlobalScope: { prototype: DedicatedWorkerGlobalScope; new(): DedicatedWorkerGlobalScope; -} +}; interface ExtendableEvent extends Event { waitUntil(f: Promise): void; @@ -1296,7 +1307,7 @@ interface ExtendableEvent extends Event { declare var ExtendableEvent: { prototype: ExtendableEvent; new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent; -} +}; interface ExtendableMessageEvent extends ExtendableEvent { readonly data: any; @@ -1309,7 +1320,7 @@ interface ExtendableMessageEvent extends ExtendableEvent { declare var ExtendableMessageEvent: { prototype: ExtendableMessageEvent; new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent; -} +}; interface FetchEvent extends ExtendableEvent { readonly clientId: string | null; @@ -1321,7 +1332,7 @@ interface FetchEvent extends ExtendableEvent { declare var FetchEvent: { prototype: FetchEvent; new(type: string, eventInitDict: FetchEventInit): FetchEvent; -} +}; interface FileReaderSync { readAsArrayBuffer(blob: Blob): any; @@ -1333,7 +1344,7 @@ interface FileReaderSync { declare var FileReaderSync: { prototype: FileReaderSync; new(): FileReaderSync; -} +}; interface NotificationEvent extends ExtendableEvent { readonly action: string; @@ -1343,7 +1354,7 @@ interface NotificationEvent extends ExtendableEvent { declare var NotificationEvent: { prototype: NotificationEvent; new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; -} +}; interface PushEvent extends ExtendableEvent { readonly data: PushMessageData | null; @@ -1352,7 +1363,7 @@ interface PushEvent extends ExtendableEvent { declare var PushEvent: { prototype: PushEvent; new(type: string, eventInitDict?: PushEventInit): PushEvent; -} +}; interface PushMessageData { arrayBuffer(): ArrayBuffer; @@ -1364,7 +1375,7 @@ interface PushMessageData { declare var PushMessageData: { prototype: PushMessageData; new(): PushMessageData; -} +}; interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "activate": ExtendableEvent; @@ -1398,7 +1409,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { declare var ServiceWorkerGlobalScope: { prototype: ServiceWorkerGlobalScope; new(): ServiceWorkerGlobalScope; -} +}; interface SyncEvent extends ExtendableEvent { readonly lastChance: boolean; @@ -1408,7 +1419,7 @@ interface SyncEvent extends ExtendableEvent { declare var SyncEvent: { prototype: SyncEvent; new(type: string, init: SyncEventInit): SyncEvent; -} +}; interface WindowClient extends Client { readonly focused: boolean; @@ -1420,7 +1431,7 @@ interface WindowClient extends Client { declare var WindowClient: { prototype: WindowClient; new(): WindowClient; -} +}; interface WorkerGlobalScopeEventMap { "error": ErrorEvent; @@ -1443,7 +1454,7 @@ interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, Glo declare var WorkerGlobalScope: { prototype: WorkerGlobalScope; new(): WorkerGlobalScope; -} +}; interface WorkerLocation { readonly hash: string; @@ -1461,7 +1472,7 @@ interface WorkerLocation { declare var WorkerLocation: { prototype: WorkerLocation; new(): WorkerLocation; -} +}; interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware { readonly hardwareConcurrency: number; @@ -1470,7 +1481,7 @@ interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, Navigato declare var WorkerNavigator: { prototype: WorkerNavigator; new(): WorkerNavigator; -} +}; interface WorkerUtils extends Object, WindowBase64 { readonly indexedDB: IDBFactory; @@ -1513,38 +1524,38 @@ interface ImageBitmap { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; -} +}; interface BlobPropertyBag { type?: string; @@ -1751,8 +1762,23 @@ interface AddEventListenerOptions extends EventListenerOptions { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; } interface PositionCallback { (position: Position): void; @@ -1760,21 +1786,6 @@ interface PositionCallback { interface PositionErrorCallback { (error: PositionError): void; } -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface FunctionStringCallback { - (data: string): void; -} -interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; -} -interface NotificationPermissionCallback { - (permission: NotificationPermission): void; -} declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any; declare function close(): void; declare function postMessage(message: any, transfer?: any[]): void; diff --git a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types index e8656beb985..b06aaa08297 100644 --- a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types +++ b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types @@ -2,9 +2,9 @@ for (const element of document.getElementsByTagName("a")) { >element : HTMLAnchorElement >document.getElementsByTagName("a") : NodeListOf ->document.getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } +>document.getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } >document : Document ->getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } +>getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } >"a" : "a" element.href; From 8894915d1ac3334716c703403ecf35e8c8e0e1d2 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 18 May 2017 10:15:37 -0700 Subject: [PATCH 264/282] buildSymbolDisplay: Handle alias parentSymbol --- src/compiler/checker.ts | 6 +++--- .../fourslash/quickInfoOnMethodOfImportEquals.ts | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 tests/cases/fourslash/quickInfoOnMethodOfImportEquals.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dde8033d1e9..aeabf816a96 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2027,7 +2027,7 @@ namespace ts { ts.forEach(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) { const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { return [symbolFromSymbolTable]; } @@ -3087,8 +3087,8 @@ namespace ts { // Write type arguments of instantiated class/interface here if (flags & SymbolFormatFlags.WriteTypeParametersOrArguments) { if (getCheckFlags(symbol) & CheckFlags.Instantiated) { - buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), - (symbol).mapper, writer, enclosingDeclaration); + const params = getTypeParametersOfClassOrInterface(symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol); + buildDisplayForTypeArgumentsAndDelimiters(params, (symbol).mapper, writer, enclosingDeclaration); } else { buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); diff --git a/tests/cases/fourslash/quickInfoOnMethodOfImportEquals.ts b/tests/cases/fourslash/quickInfoOnMethodOfImportEquals.ts new file mode 100644 index 00000000000..d4078020add --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnMethodOfImportEquals.ts @@ -0,0 +1,16 @@ +/// + +// Test for https://github.com/Microsoft/TypeScript/issues/15931 + +// @Filename: /a.d.ts +////declare class C { +//// m(): void; +////} +////export = C; + +// @Filename: /b.ts +////import C = require("./a"); +////declare var x: C; +////x./**/m; + +verify.quickInfoAt("", "(method) C.m(): void", undefined); From 3690926e627e6197e8e0f5c2c62b9f546cbd1cb2 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 22 May 2017 09:34:21 -0700 Subject: [PATCH 265/282] In path mapping module resolution, try loading from path as directory even if it has an extension --- src/compiler/moduleNameResolver.ts | 10 +++-- ...sedModuleResolution_withExtensionInName.js | 16 ++++++++ ...duleResolution_withExtensionInName.symbols | 15 ++++++++ ...eResolution_withExtensionInName.trace.json | 38 +++++++++++++++++++ ...ModuleResolution_withExtensionInName.types | 15 ++++++++ ...tion_withExtension_failedLookup.trace.json | 2 + ...sedModuleResolution_withExtensionInName.ts | 23 +++++++++++ 7 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.types create mode 100644 tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index e4edfe68dfa..4c6616c36d4 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -653,11 +653,13 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } - // A path mapping may have a ".ts" extension; in contrast to an import, which should omit it. - const tsExtension = tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { + // A path mapping may have an extension, in contrast to an import, which should omit it. + const extension = tryGetExtensionFromPath(candidate); + if (extension !== undefined) { const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - return path && { path, extension: tsExtension }; + if (path !== undefined) { + return { path, extension }; + } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.js b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.js new file mode 100644 index 00000000000..c54c0ba61ed --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.js @@ -0,0 +1,16 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts] //// + +//// [index.d.ts] +export const x: number; + +//// [index.d.ts] +export const y: number; + +//// [a.ts] +import { x } from "zone.js"; +import { y } from "zone.tsx"; + + +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.symbols new file mode 100644 index 00000000000..440ef2d2942 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.symbols @@ -0,0 +1,15 @@ +=== /a.ts === +import { x } from "zone.js"; +>x : Symbol(x, Decl(a.ts, 0, 8)) + +import { y } from "zone.tsx"; +>y : Symbol(y, Decl(a.ts, 1, 8)) + +=== /foo/zone.js/index.d.ts === +export const x: number; +>x : Symbol(x, Decl(index.d.ts, 0, 12)) + +=== /foo/zone.tsx/index.d.ts === +export const y: number; +>y : Symbol(y, Decl(index.d.ts, 0, 12)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.trace.json new file mode 100644 index 00000000000..216442fb378 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.trace.json @@ -0,0 +1,38 @@ +[ + "======== Resolving module 'zone.js' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'zone.js'.", + "'paths' option is specified, looking for a pattern to match module name 'zone.js'.", + "Module name 'zone.js', matched pattern '*'.", + "Trying substitution 'foo/*', candidate module location: 'foo/zone.js'.", + "File '/foo/zone.js' does not exist.", + "Loading module as file / folder, candidate module location '/foo/zone.js', target file type 'TypeScript'.", + "File '/foo/zone.js.ts' does not exist.", + "File '/foo/zone.js.tsx' does not exist.", + "File '/foo/zone.js.d.ts' does not exist.", + "File name '/foo/zone.js' has a '.js' extension - stripping it.", + "File '/foo/zone.ts' does not exist.", + "File '/foo/zone.tsx' does not exist.", + "File '/foo/zone.d.ts' does not exist.", + "File '/foo/zone.js/package.json' does not exist.", + "File '/foo/zone.js/index.ts' does not exist.", + "File '/foo/zone.js/index.tsx' does not exist.", + "File '/foo/zone.js/index.d.ts' exist - use it as a name resolution result.", + "======== Module name 'zone.js' was successfully resolved to '/foo/zone.js/index.d.ts'. ========", + "======== Resolving module 'zone.tsx' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'zone.tsx'.", + "'paths' option is specified, looking for a pattern to match module name 'zone.tsx'.", + "Module name 'zone.tsx', matched pattern '*'.", + "Trying substitution 'foo/*', candidate module location: 'foo/zone.tsx'.", + "File '/foo/zone.tsx' does not exist.", + "Loading module as file / folder, candidate module location '/foo/zone.tsx', target file type 'TypeScript'.", + "File '/foo/zone.tsx.ts' does not exist.", + "File '/foo/zone.tsx.tsx' does not exist.", + "File '/foo/zone.tsx.d.ts' does not exist.", + "File '/foo/zone.tsx/package.json' does not exist.", + "File '/foo/zone.tsx/index.ts' does not exist.", + "File '/foo/zone.tsx/index.tsx' does not exist.", + "File '/foo/zone.tsx/index.d.ts' exist - use it as a name resolution result.", + "======== Module name 'zone.tsx' was successfully resolved to '/foo/zone.tsx/index.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.types b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.types new file mode 100644 index 00000000000..7fd8a2710c6 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtensionInName.types @@ -0,0 +1,15 @@ +=== /a.ts === +import { x } from "zone.js"; +>x : number + +import { y } from "zone.tsx"; +>y : number + +=== /foo/zone.js/index.d.ts === +export const x: number; +>x : number + +=== /foo/zone.tsx/index.d.ts === +export const y: number; +>y : number + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json index 7561a47b1e7..803520f12fd 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json @@ -6,6 +6,7 @@ "Module name 'foo', matched pattern 'foo'.", "Trying substitution 'foo/foo.ts', candidate module location: 'foo/foo.ts'.", "File '/foo/foo.ts' does not exist.", + "Loading module as file / folder, candidate module location '/foo/foo.ts', target file type 'TypeScript'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", "Directory '/node_modules' does not exist, skipping all lookups in it.", "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'foo'.", @@ -13,6 +14,7 @@ "Module name 'foo', matched pattern 'foo'.", "Trying substitution 'foo/foo.ts', candidate module location: 'foo/foo.ts'.", "File '/foo/foo.ts' does not exist.", + "Loading module as file / folder, candidate module location '/foo/foo.ts', target file type 'JavaScript'.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", "Directory '/node_modules' does not exist, skipping all lookups in it.", "======== Module name 'foo' was not resolved. ========" diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts new file mode 100644 index 00000000000..675003fe142 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtensionInName.ts @@ -0,0 +1,23 @@ +// @traceResolution: true +// @module: commonjs +// @noImplicitReferences: true + +// @filename: /tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "*": ["foo/*"] + } + } +} + +// @filename: /foo/zone.js/index.d.ts +export const x: number; + +// @filename: /foo/zone.tsx/index.d.ts +export const y: number; + +// @filename: /a.ts +import { x } from "zone.js"; +import { y } from "zone.tsx"; From bf7e3229cfb7a824f55ab23c03d06e8329e78946 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 23 May 2017 09:12:03 -0700 Subject: [PATCH 266/282] Fix typo: symbol -> parentSymbol --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index aeabf816a96..8df64ef4356 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3087,7 +3087,7 @@ namespace ts { // Write type arguments of instantiated class/interface here if (flags & SymbolFormatFlags.WriteTypeParametersOrArguments) { if (getCheckFlags(symbol) & CheckFlags.Instantiated) { - const params = getTypeParametersOfClassOrInterface(symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol); + const params = getTypeParametersOfClassOrInterface(parentSymbol.flags & SymbolFlags.Alias ? resolveAlias(parentSymbol) : parentSymbol); buildDisplayForTypeArgumentsAndDelimiters(params, (symbol).mapper, writer, enclosingDeclaration); } else { From 7b0bd090e28c5e19143c2823dfcc10c5ea4e392e Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 23 May 2017 08:52:55 -0700 Subject: [PATCH 267/282] findAllReferences: Make "isWriteAccess" handle special declaration kinds --- src/compiler/checker.ts | 4 ++-- src/compiler/utilities.ts | 17 ++++++++++++++ src/services/findAllReferences.ts | 22 +++++++++---------- .../fourslash/findAllRefsForModuleGlobal.ts | 2 +- ...rencesIsDefinitionOfNumberNamedProperty.ts | 2 +- ...rencesIsDefinitionOfStringNamedProperty.ts | 2 +- .../cases/fourslash/referencesBloomFilters.ts | 2 +- .../fourslash/referencesBloomFilters2.ts | 4 ++-- .../fourslash/referencesBloomFilters3.ts | 2 +- .../cases/fourslash/referencesForAmbients.ts | 4 ++-- tests/cases/fourslash/referencesForEnums.ts | 4 ++-- .../referencesForExternalModuleNames.ts | 2 +- ...eferencesForNumericLiteralPropertyNames.ts | 6 ++--- ...referencesForStringLiteralPropertyNames.ts | 4 ++-- ...eferencesForStringLiteralPropertyNames2.ts | 2 +- ...eferencesForStringLiteralPropertyNames3.ts | 4 ++-- ...eferencesForStringLiteralPropertyNames4.ts | 2 +- tests/cases/fourslash/renameJsExports01.ts | 2 +- 18 files changed, 51 insertions(+), 36 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8551652c176..46f56d99b39 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12750,7 +12750,7 @@ namespace ts { function getContextualTypeForBinaryOperand(node: Expression): Type { const binaryExpression = node.parent; const operator = binaryExpression.operatorToken.kind; - if (operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { + if (isAssignmentOperator(operator)) { // Don't do this for special property assignments to avoid circularity if (getSpecialPropertyAssignmentKind(binaryExpression) !== SpecialPropertyAssignmentKind.None) { return undefined; @@ -17305,7 +17305,7 @@ namespace ts { } function checkAssignmentOperator(valueType: Type): void { - if (produceDiagnostics && operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { + if (produceDiagnostics && isAssignmentOperator(operator)) { // TypeScript 1.0 spec (April 2014): 4.17 // An assignment of the form // VarExpr = ValueExpr diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index a5750248707..3a8b8b59f7d 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1785,6 +1785,23 @@ namespace ts { } } + /* @internal */ + // See GH#16030 + export function isAnyDeclarationName(name: Node): boolean { + switch (name.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + if (isDeclaration(name.parent)) { + return name.parent.name === name; + } + const binExp = name.parent.parent; + return isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None && getNameOfDeclaration(binExp) === name; + default: + return false; + } + } + export function isLiteralComputedPropertyDeclarationName(node: Node) { return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) && node.parent.kind === SyntaxKind.ComputedPropertyName && diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index fd564cac13d..efc6a6f6ed1 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -176,7 +176,7 @@ namespace ts.FindAllReferences { fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), isWriteAccess: isWriteAccess(node), - isDefinition: isDeclarationName(node) || isLiteralComputedPropertyDeclarationName(node), + isDefinition: isAnyDeclarationName(node) || isLiteralComputedPropertyDeclarationName(node), isInString }; } @@ -242,22 +242,20 @@ namespace ts.FindAllReferences { /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccess(node: Node): boolean { - if (node.kind === SyntaxKind.Identifier && isDeclarationName(node)) { + if (isAnyDeclarationName(node)) { return true; } - const parent = node.parent; - if (parent) { - if (parent.kind === SyntaxKind.PostfixUnaryExpression || parent.kind === SyntaxKind.PrefixUnaryExpression) { + const { parent } = node; + switch (parent && parent.kind) { + case SyntaxKind.PostfixUnaryExpression: + case SyntaxKind.PrefixUnaryExpression: return true; - } - else if (parent.kind === SyntaxKind.BinaryExpression && (parent).left === node) { - const operator = (parent).operatorToken.kind; - return SyntaxKind.FirstAssignment <= operator && operator <= SyntaxKind.LastAssignment; - } + case SyntaxKind.BinaryExpression: + return (parent).left === node && isAssignmentOperator((parent).operatorToken.kind); + default: + return false; } - - return false; } } diff --git a/tests/cases/fourslash/findAllRefsForModuleGlobal.ts b/tests/cases/fourslash/findAllRefsForModuleGlobal.ts index 25c23faeae5..4c1b39cdb0f 100644 --- a/tests/cases/fourslash/findAllRefsForModuleGlobal.ts +++ b/tests/cases/fourslash/findAllRefsForModuleGlobal.ts @@ -6,7 +6,7 @@ // @Filename: /b.ts /////// ////import { x } from "[|foo|]"; -////declare module "[|{| "isDefinition": true |}foo|]" {} +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}foo|]" {} verify.noErrors(); diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts index c603f398e5e..b391deec9cc 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfNumberNamedProperty.ts @@ -1,5 +1,5 @@ /// -////let o = { [|{| "isDefinition": true |}1|]: 12 }; +////let o = { [|{| "isWriteAccess": true, "isDefinition": true |}1|]: 12 }; ////let y = o[[|1|]]; const ranges = test.ranges(); diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts index 43fe0c571fc..4b842da6f59 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfStringNamedProperty.ts @@ -1,5 +1,5 @@ /// -////let o = { "[|{| "isDefinition": true |}x|]": 12 }; +////let o = { "[|{| "isWriteAccess": true, "isDefinition": true |}x|]": 12 }; ////let y = o.[|x|]; const ranges = test.ranges(); diff --git a/tests/cases/fourslash/referencesBloomFilters.ts b/tests/cases/fourslash/referencesBloomFilters.ts index c9f290db0db..2745f6144ca 100644 --- a/tests/cases/fourslash/referencesBloomFilters.ts +++ b/tests/cases/fourslash/referencesBloomFilters.ts @@ -12,7 +12,7 @@ ////function blah2() { container["[|searchProp|]"] }; // @Filename: redeclaration.ts -////container = { "[|{| "isDefinition": true |}searchProp|]" : 18 }; +////container = { "[|{| "isWriteAccess": true, "isDefinition": true |}searchProp|]" : 18 }; const ranges = test.ranges(); const [r0, r1, r2, r3] = ranges; diff --git a/tests/cases/fourslash/referencesBloomFilters2.ts b/tests/cases/fourslash/referencesBloomFilters2.ts index daf60d0dd01..26690e437ee 100644 --- a/tests/cases/fourslash/referencesBloomFilters2.ts +++ b/tests/cases/fourslash/referencesBloomFilters2.ts @@ -3,7 +3,7 @@ // Ensure BloomFilter building logic is correct, by having one reference per file // @Filename: declaration.ts -////var container = { [|{| "isDefinition": true |}42|]: 1 }; +////var container = { [|{| "isWriteAccess": true, "isDefinition": true |}42|]: 1 }; // @Filename: expression.ts ////function blah() { return (container[[|42|]]) === 2; }; @@ -12,7 +12,7 @@ ////function blah2() { container["[|42|]"] }; // @Filename: redeclaration.ts -////container = { "[|{| "isDefinition": true |}42|]" : 18 }; +////container = { "[|{| "isWriteAccess": true, "isDefinition": true |}42|]" : 18 }; const ranges = test.ranges(); const [r0, r1, r2, r3] = ranges; diff --git a/tests/cases/fourslash/referencesBloomFilters3.ts b/tests/cases/fourslash/referencesBloomFilters3.ts index 0dd5c645264..d7d335cde02 100644 --- a/tests/cases/fourslash/referencesBloomFilters3.ts +++ b/tests/cases/fourslash/referencesBloomFilters3.ts @@ -4,7 +4,7 @@ // @Filename: declaration.ts -////enum Test { "[|{| "isDefinition": true |}42|]" = 1 }; +////enum Test { "[|{| "isWriteAccess": true, "isDefinition": true |}42|]" = 1 }; // @Filename: expression.ts ////(Test[[|42|]]); diff --git a/tests/cases/fourslash/referencesForAmbients.ts b/tests/cases/fourslash/referencesForAmbients.ts index f5789716155..2397738581e 100644 --- a/tests/cases/fourslash/referencesForAmbients.ts +++ b/tests/cases/fourslash/referencesForAmbients.ts @@ -1,10 +1,10 @@ /// -////declare module "[|{| "isDefinition": true |}foo|]" { +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}foo|]" { //// var [|{| "isWriteAccess": true, "isDefinition": true |}f|]: number; ////} //// -////declare module "[|{| "isDefinition": true |}bar|]" { +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}bar|]" { //// export import [|{| "isWriteAccess": true, "isDefinition": true |}foo|] = require("[|foo|]"); //// var f2: typeof [|foo|].[|f|]; ////} diff --git a/tests/cases/fourslash/referencesForEnums.ts b/tests/cases/fourslash/referencesForEnums.ts index 68face36d04..af4fec8aae8 100644 --- a/tests/cases/fourslash/referencesForEnums.ts +++ b/tests/cases/fourslash/referencesForEnums.ts @@ -2,8 +2,8 @@ ////enum E { //// [|{| "isWriteAccess": true, "isDefinition": true |}value1|] = 1, -//// "[|{| "isDefinition": true |}value2|]" = [|value1|], -//// [|{| "isDefinition": true |}111|] = 11 +//// "[|{| "isWriteAccess": true, "isDefinition": true |}value2|]" = [|value1|], +//// [|{| "isWriteAccess": true, "isDefinition": true |}111|] = 11 ////} //// ////E.[|value1|]; diff --git a/tests/cases/fourslash/referencesForExternalModuleNames.ts b/tests/cases/fourslash/referencesForExternalModuleNames.ts index 75ea9e908cf..127aa9fd657 100644 --- a/tests/cases/fourslash/referencesForExternalModuleNames.ts +++ b/tests/cases/fourslash/referencesForExternalModuleNames.ts @@ -3,7 +3,7 @@ // Global interface reference. // @Filename: referencesForGlobals_1.ts -////declare module "[|{| "isDefinition": true |}foo|]" { +////declare module "[|{| "isWriteAccess": true, "isDefinition": true |}foo|]" { //// var f: number; ////} diff --git a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts index effa4abc164..a869ba8bcc1 100644 --- a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts +++ b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts @@ -1,13 +1,13 @@ /// ////class Foo { -//// public [|{| "isDefinition": true |}12|]: any; +//// public [|{| "isWriteAccess": true, "isDefinition": true |}12|]: any; ////} //// ////var x: Foo; ////x[[|12|]]; -////x = { "[|{| "isDefinition": true |}12|]": 0 }; -////x = { [|{| "isDefinition": true |}12|]: 0 }; +////x = { "[|{| "isWriteAccess": true, "isDefinition": true |}12|]": 0 }; +////x = { [|{| "isWriteAccess": true, "isDefinition": true |}12|]: 0 }; //verify.singleReferenceGroup("(property) Foo[12]: any"); const ranges = test.ranges(); diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts index e9be352f819..c5ae2f0c586 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts @@ -1,13 +1,13 @@ /// ////class Foo { -//// public "[|{| "isDefinition": true |}ss|]": any; +//// public "[|{| "isWriteAccess": true, "isDefinition": true |}ss|]": any; ////} //// ////var x: Foo; ////x.[|ss|]; ////x["[|ss|]"]; -////x = { "[|{| "isDefinition": true |}ss|]": 0 }; +////x = { "[|{| "isWriteAccess": true, "isDefinition": true |}ss|]": 0 }; ////x = { [|{| "isWriteAccess": true, "isDefinition": true |}ss|]: 0 }; const ranges = test.ranges(); diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts index 6fbb0b85072..89b6c7c755e 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames2.ts @@ -1,7 +1,7 @@ /// ////class Foo { -//// "[|{| "isDefinition": true |}blah|]"() { return 0; } +//// "[|{| "isWriteAccess": true, "isDefinition": true |}blah|]"() { return 0; } ////} //// ////var x: Foo; diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts index d4e12a67afc..aae15afd0c7 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames3.ts @@ -1,8 +1,8 @@ /// ////class Foo2 { -//// get "[|{| "isDefinition": true |}42|]"() { return 0; } -//// set [|{| "isDefinition": true |}42|](n) { } +//// get "[|{| "isWriteAccess": true, "isDefinition": true |}42|]"() { return 0; } +//// set [|{| "isWriteAccess": true, "isDefinition": true |}42|](n) { } ////} //// ////var y: Foo2; diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts index efe8972f2c7..4293435de1d 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames4.ts @@ -1,6 +1,6 @@ /// -////var x = { "[|{| "isDefinition": true |}someProperty|]": 0 } +////var x = { "[|{| "isWriteAccess": true, "isDefinition": true |}someProperty|]": 0 } ////x["[|someProperty|]"] = 3; ////x.[|someProperty|] = 5; diff --git a/tests/cases/fourslash/renameJsExports01.ts b/tests/cases/fourslash/renameJsExports01.ts index b731ece63f3..e1b71d232a6 100644 --- a/tests/cases/fourslash/renameJsExports01.ts +++ b/tests/cases/fourslash/renameJsExports01.ts @@ -2,7 +2,7 @@ // @allowJs: true // @Filename: a.js -////exports.[|area|] = function (r) { return r * r; } +////exports.[|{| "isWriteAccess": true, "isDefinition": true |}area|] = function (r) { return r * r; } // @Filename: b.js ////var mod = require('./a'); From f8aae8915704d815c637eb9557bb6553fc11ca23 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Tue, 23 May 2017 18:54:02 +0200 Subject: [PATCH 268/282] Update more return types to include undefined (#15903) * Update more return types * Update types of forEachChild callbacks * fix line endings --- src/compiler/checker.ts | 6 +++--- src/compiler/parser.ts | 8 ++++---- src/compiler/types.ts | 8 ++++---- src/services/jsDoc.ts | 4 ++-- src/services/services.ts | 32 ++++++++++++++++---------------- src/services/types.ts | 16 ++++++++-------- 6 files changed, 37 insertions(+), 37 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8551652c176..6fe27e9dca9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6074,7 +6074,7 @@ namespace ts { * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type: Type, name: string): Symbol { + function getPropertyOfType(type: Type, name: string): Symbol | undefined { type = getApparentType(type); if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); @@ -6112,14 +6112,14 @@ namespace ts { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function getIndexInfoOfStructuredType(type: Type, kind: IndexKind): IndexInfo { + function getIndexInfoOfStructuredType(type: Type, kind: IndexKind): IndexInfo | undefined { if (type.flags & TypeFlags.StructuredType) { const resolved = resolveStructuredTypeMembers(type); return kind === IndexKind.String ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } - function getIndexTypeOfStructuredType(type: Type, kind: IndexKind): Type { + function getIndexTypeOfStructuredType(type: Type, kind: IndexKind): Type | undefined { const info = getIndexInfoOfStructuredType(type, kind); return info && info.type; } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 36f08b0b184..87bd36ee3a0 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -23,19 +23,19 @@ namespace ts { } } - function visitNode(cbNode: (node: Node) => T, node: Node): T | undefined { + function visitNode(cbNode: (node: Node) => T, node?: Node): T | undefined { if (node) { return cbNode(node); } } - function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes: Node[]): T | undefined { + function visitNodeArray(cbNodes: (nodes: Node[]) => T, nodes?: Node[]): T | undefined { if (nodes) { return cbNodes(nodes); } } - function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]): T | undefined { + function visitEachNode(cbNode: (node: Node) => T, nodes?: Node[]): T | undefined { if (nodes) { for (const node of nodes) { const result = cbNode(node); @@ -57,7 +57,7 @@ namespace ts { // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray // callback parameters, but that causes a closure allocation for each invocation with noticeable effects // on performance. - const visitNodes: (cb: ((node: Node) => T) | ((node: Node[]) => T), nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; + const visitNodes: (cb: ((node?: Node) => T | undefined) | ((node?: Node[]) => T | undefined), nodes?: Node[]) => T | undefined = cbNodeArray ? visitNodeArray : visitEachNode; const cbNodes = cbNodeArray || cbNode; switch (node.kind) { case SyntaxKind.QualifiedName: diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 98efa1f3e53..a8da09a11c5 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2506,10 +2506,10 @@ namespace ts { getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; - getPropertyOfType(type: Type, propertyName: string): Symbol; - getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo; + getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; + getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; - getIndexTypeOfType(type: Type, kind: IndexKind): Type; + getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; getBaseTypes(type: InterfaceType): BaseType[]; getBaseTypeOfLiteralType(type: Type): Type; getWidenedType(type: Type): Type; @@ -3293,7 +3293,7 @@ namespace ts { export interface Signature { declaration: SignatureDeclaration; // Originating declaration - typeParameters?: TypeParameter[]; // Type parameters (undefined if non-generic) + typeParameters?: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters /* @internal */ thisParameter?: Symbol; // symbol of this-type parameter diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index b130a7f754b..8ca55029603 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -44,7 +44,7 @@ namespace ts.JsDoc { let jsDocTagNameCompletionEntries: CompletionEntry[]; let jsDocTagCompletionEntries: CompletionEntry[]; - export function getJsDocCommentsFromDeclarations(declarations: Declaration[]) { + export function getJsDocCommentsFromDeclarations(declarations?: Declaration[]) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter @@ -69,7 +69,7 @@ namespace ts.JsDoc { return documentationComment; } - export function getJsDocTagsFromDeclarations(declarations: Declaration[]) { + export function getJsDocTagsFromDeclarations(declarations?: Declaration[]) { // Only collect doc comments from duplicate declarations once. const tags: JSDocTagInfo[] = []; forEachUnique(declarations, declaration => { diff --git a/src/services/services.ts b/src/services/services.ts index aca13d7469e..05fe59084b4 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -309,15 +309,15 @@ namespace ts { class SymbolObject implements Symbol { flags: SymbolFlags; name: string; - declarations: Declaration[]; + declarations?: Declaration[]; // Undefined is used to indicate the value has not been computed. If, after computing, the - // symbol has no doc comment, then the empty string will be returned. - documentationComment: SymbolDisplayPart[]; + // symbol has no doc comment, then the empty array will be returned. + documentationComment?: SymbolDisplayPart[]; // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no JSDoc tags, then the empty array will be returned. - tags: JSDocTagInfo[]; + tags?: JSDocTagInfo[]; constructor(flags: SymbolFlags, name: string) { this.flags = flags; @@ -332,7 +332,7 @@ namespace ts { return this.name; } - getDeclarations(): Declaration[] { + getDeclarations(): Declaration[] | undefined { return this.declarations; } @@ -383,7 +383,7 @@ namespace ts { flags: TypeFlags; objectFlags?: ObjectFlags; id: number; - symbol: Symbol; + symbol?: Symbol; constructor(checker: TypeChecker, flags: TypeFlags) { this.checker = checker; this.flags = flags; @@ -391,13 +391,13 @@ namespace ts { getFlags(): TypeFlags { return this.flags; } - getSymbol(): Symbol { + getSymbol(): Symbol | undefined { return this.symbol; } getProperties(): Symbol[] { return this.checker.getPropertiesOfType(this); } - getProperty(propertyName: string): Symbol { + getProperty(propertyName: string): Symbol | undefined { return this.checker.getPropertyOfType(this, propertyName); } getApparentProperties(): Symbol[] { @@ -409,13 +409,13 @@ namespace ts { getConstructSignatures(): Signature[] { return this.checker.getSignaturesOfType(this, SignatureKind.Construct); } - getStringIndexType(): Type { + getStringIndexType(): Type | undefined { return this.checker.getIndexTypeOfType(this, IndexKind.String); } - getNumberIndexType(): Type { + getNumberIndexType(): Type | undefined { return this.checker.getIndexTypeOfType(this, IndexKind.Number); } - getBaseTypes(): BaseType[] { + getBaseTypes(): BaseType[] | undefined { return this.flags & TypeFlags.Object && this.objectFlags & (ObjectFlags.Class | ObjectFlags.Interface) ? this.checker.getBaseTypes(this) : undefined; @@ -428,7 +428,7 @@ namespace ts { class SignatureObject implements Signature { checker: TypeChecker; declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; + typeParameters?: TypeParameter[]; parameters: Symbol[]; thisParameter: Symbol; resolvedReturnType: Type; @@ -438,12 +438,12 @@ namespace ts { hasLiteralTypes: boolean; // Undefined is used to indicate the value has not been computed. If, after computing, the - // symbol has no doc comment, then the empty string will be returned. - documentationComment: SymbolDisplayPart[]; + // symbol has no doc comment, then the empty array will be returned. + documentationComment?: SymbolDisplayPart[]; // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no doc comment, then the empty array will be returned. - jsDocTags: JSDocTagInfo[]; + jsDocTags?: JSDocTagInfo[]; constructor(checker: TypeChecker) { this.checker = checker; @@ -451,7 +451,7 @@ namespace ts { getDeclaration(): SignatureDeclaration { return this.declaration; } - getTypeParameters(): TypeParameter[] { + getTypeParameters(): TypeParameter[] | undefined { return this.typeParameters; } getParameters(): Symbol[] { diff --git a/src/services/types.ts b/src/services/types.ts index 6e6fa245e37..e042276e650 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -19,34 +19,34 @@ namespace ts { getFirstToken(sourceFile?: SourceFile): Node; getLastToken(sourceFile?: SourceFile): Node; // See ts.forEachChild for documentation. - forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; } export interface Symbol { getFlags(): SymbolFlags; getName(): string; - getDeclarations(): Declaration[]; + getDeclarations(): Declaration[] | undefined; getDocumentationComment(): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } export interface Type { getFlags(): TypeFlags; - getSymbol(): Symbol; + getSymbol(): Symbol | undefined; getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol; + getProperty(propertyName: string): Symbol | undefined; getApparentProperties(): Symbol[]; getCallSignatures(): Signature[]; getConstructSignatures(): Signature[]; - getStringIndexType(): Type; - getNumberIndexType(): Type; - getBaseTypes(): BaseType[]; + getStringIndexType(): Type | undefined; + getNumberIndexType(): Type | undefined; + getBaseTypes(): BaseType[] | undefined; getNonNullableType(): Type; } export interface Signature { getDeclaration(): SignatureDeclaration; - getTypeParameters(): TypeParameter[]; + getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; From e4aa515191f0817ca64374e3da1e80418f8444b0 Mon Sep 17 00:00:00 2001 From: Yui Date: Tue, 23 May 2017 10:24:46 -0700 Subject: [PATCH 269/282] [Master] Fix 15179 missing comment in switch case clause (#16033) * Fix emit comments after switch case clause * Update baselines * Add new tests and baselines --- src/compiler/emitter.ts | 16 ++++++++ .../reference/commentsAfterCaseClauses1.js | 31 ++++++++++++++ .../commentsAfterCaseClauses1.symbols | 20 +++++++++ .../reference/commentsAfterCaseClauses1.types | 37 +++++++++++++++++ .../reference/commentsAfterCaseClauses2.js | 36 ++++++++++++++++ .../commentsAfterCaseClauses2.symbols | 23 +++++++++++ .../reference/commentsAfterCaseClauses2.types | 41 +++++++++++++++++++ .../reference/commentsAfterCaseClauses3.js | 34 +++++++++++++++ .../commentsAfterCaseClauses3.symbols | 22 ++++++++++ .../reference/commentsAfterCaseClauses3.types | 39 ++++++++++++++++++ .../baselines/reference/parserRealSource1.js | 16 ++++---- tests/baselines/reference/parserindenter.js | 8 ++-- .../switchStatementsWithMultipleDefaults.js | 6 +-- .../switchStatementsWithMultipleDefaults1.js | 2 +- .../compiler/commentsAfterCaseClauses1.ts | 14 +++++++ .../compiler/commentsAfterCaseClauses2.ts | 17 ++++++++ .../compiler/commentsAfterCaseClauses3.ts | 16 ++++++++ 17 files changed, 362 insertions(+), 16 deletions(-) create mode 100644 tests/baselines/reference/commentsAfterCaseClauses1.js create mode 100644 tests/baselines/reference/commentsAfterCaseClauses1.symbols create mode 100644 tests/baselines/reference/commentsAfterCaseClauses1.types create mode 100644 tests/baselines/reference/commentsAfterCaseClauses2.js create mode 100644 tests/baselines/reference/commentsAfterCaseClauses2.symbols create mode 100644 tests/baselines/reference/commentsAfterCaseClauses2.types create mode 100644 tests/baselines/reference/commentsAfterCaseClauses3.js create mode 100644 tests/baselines/reference/commentsAfterCaseClauses3.symbols create mode 100644 tests/baselines/reference/commentsAfterCaseClauses3.types create mode 100644 tests/cases/compiler/commentsAfterCaseClauses1.ts create mode 100644 tests/cases/compiler/commentsAfterCaseClauses2.ts create mode 100644 tests/cases/compiler/commentsAfterCaseClauses3.ts diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 0348469dae1..c0b0d170de8 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2021,6 +2021,22 @@ namespace ts { rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile) ); + // e.g: + // case 0: // Zero + // case 1: // One + // case 2: // two + // return "hi"; + // If there is no statements, emitNodeWithComments of the parentNode which is caseClause will take care of trailing comment. + // So in example above, comment "// Zero" and "// One" will be emit in emitTrailingComments in emitNodeWithComments. + // However, for "case 2", because parentNode which is caseClause has an "end" property to be end of the statements (in this case return statement) + // comment "// two" will not be emitted in emitNodeWithComments. + // Therefore, we have to do the check here to emit such comment. + if (statements.length > 0) { + // We use emitTrailingCommentsOfPosition instead of emitLeadingCommentsOfPosition because leading comments is defined as comments before the node after newline character separating it from previous line + // Note: we can't use parentNode.end as such position includes statements. + emitTrailingCommentsOfPosition(statements.pos); + } + if (emitAsSingleStatement) { write(" "); emit(statements[0]); diff --git a/tests/baselines/reference/commentsAfterCaseClauses1.js b/tests/baselines/reference/commentsAfterCaseClauses1.js new file mode 100644 index 00000000000..e12fe703335 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses1.js @@ -0,0 +1,31 @@ +//// [commentsAfterCaseClauses1.ts] +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + return "Hi"; + case 3: // three + case 4 : // four + return "hello"; + case 5: // five + default: // default + return "world"; + } +} + +//// [commentsAfterCaseClauses1.js] +function getSecurity(level) { + switch (level) { + case 0: // Zero + case 1: // one + case 2:// two + return "Hi"; + case 3: // three + case 4:// four + return "hello"; + case 5: // five + default:// default + return "world"; + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses1.symbols b/tests/baselines/reference/commentsAfterCaseClauses1.symbols new file mode 100644 index 00000000000..1ca620c4eb4 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses1.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/commentsAfterCaseClauses1.ts === +function getSecurity(level) { +>getSecurity : Symbol(getSecurity, Decl(commentsAfterCaseClauses1.ts, 0, 0)) +>level : Symbol(level, Decl(commentsAfterCaseClauses1.ts, 0, 21)) + + switch(level){ +>level : Symbol(level, Decl(commentsAfterCaseClauses1.ts, 0, 21)) + + case 0: // Zero + case 1: // one + case 2: // two + return "Hi"; + case 3: // three + case 4 : // four + return "hello"; + case 5: // five + default: // default + return "world"; + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses1.types b/tests/baselines/reference/commentsAfterCaseClauses1.types new file mode 100644 index 00000000000..c7759f1c2e6 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses1.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/commentsAfterCaseClauses1.ts === +function getSecurity(level) { +>getSecurity : (level: any) => "Hi" | "hello" | "world" +>level : any + + switch(level){ +>level : any + + case 0: // Zero +>0 : 0 + + case 1: // one +>1 : 1 + + case 2: // two +>2 : 2 + + return "Hi"; +>"Hi" : "Hi" + + case 3: // three +>3 : 3 + + case 4 : // four +>4 : 4 + + return "hello"; +>"hello" : "hello" + + case 5: // five +>5 : 5 + + default: // default + return "world"; +>"world" : "world" + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses2.js b/tests/baselines/reference/commentsAfterCaseClauses2.js new file mode 100644 index 00000000000..44cd3c0da74 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses2.js @@ -0,0 +1,36 @@ +//// [commentsAfterCaseClauses2.ts] +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + // Leading comments + return "Hi"; + case 3: // three + case 4: // four + return "hello"; + case 5: // five + default: // default + return "world"; + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} + +//// [commentsAfterCaseClauses2.js] +function getSecurity(level) { + switch (level) { + case 0: // Zero + case 1: // one + case 2:// two + // Leading comments + return "Hi"; + case 3: // three + case 4:// four + return "hello"; + case 5: // five + default:// default + return "world"; + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses2.symbols b/tests/baselines/reference/commentsAfterCaseClauses2.symbols new file mode 100644 index 00000000000..b68cf18c1b9 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses2.symbols @@ -0,0 +1,23 @@ +=== tests/cases/compiler/commentsAfterCaseClauses2.ts === +function getSecurity(level) { +>getSecurity : Symbol(getSecurity, Decl(commentsAfterCaseClauses2.ts, 0, 0)) +>level : Symbol(level, Decl(commentsAfterCaseClauses2.ts, 0, 21)) + + switch(level){ +>level : Symbol(level, Decl(commentsAfterCaseClauses2.ts, 0, 21)) + + case 0: // Zero + case 1: // one + case 2: // two + // Leading comments + return "Hi"; + case 3: // three + case 4: // four + return "hello"; + case 5: // five + default: // default + return "world"; + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses2.types b/tests/baselines/reference/commentsAfterCaseClauses2.types new file mode 100644 index 00000000000..3b2d2e7688a --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses2.types @@ -0,0 +1,41 @@ +=== tests/cases/compiler/commentsAfterCaseClauses2.ts === +function getSecurity(level) { +>getSecurity : (level: any) => "Hi" | "hello" | "world" +>level : any + + switch(level){ +>level : any + + case 0: // Zero +>0 : 0 + + case 1: // one +>1 : 1 + + case 2: // two +>2 : 2 + + // Leading comments + return "Hi"; +>"Hi" : "Hi" + + case 3: // three +>3 : 3 + + case 4: // four +>4 : 4 + + return "hello"; +>"hello" : "hello" + + case 5: // five +>5 : 5 + + default: // default + return "world"; +>"world" : "world" + + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses3.js b/tests/baselines/reference/commentsAfterCaseClauses3.js new file mode 100644 index 00000000000..9538ad06c4f --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses3.js @@ -0,0 +1,34 @@ +//// [commentsAfterCaseClauses3.ts] +function getSecurity(level) { + switch(level){ + case 0: /*Zero*/ + case 1: /*One*/ + case 2: /*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4: /*four*/ + return "hello"; + case 5: /*five*/ + default: /*six*/ + return "world"; + } + +} + +//// [commentsAfterCaseClauses3.js] +function getSecurity(level) { + switch (level) { + case 0: /*Zero*/ + case 1: /*One*/ + case 2:/*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4:/*four*/ + return "hello"; + case 5: /*five*/ + default:/*six*/ + return "world"; + } +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses3.symbols b/tests/baselines/reference/commentsAfterCaseClauses3.symbols new file mode 100644 index 00000000000..73151cffdd8 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses3.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/commentsAfterCaseClauses3.ts === +function getSecurity(level) { +>getSecurity : Symbol(getSecurity, Decl(commentsAfterCaseClauses3.ts, 0, 0)) +>level : Symbol(level, Decl(commentsAfterCaseClauses3.ts, 0, 21)) + + switch(level){ +>level : Symbol(level, Decl(commentsAfterCaseClauses3.ts, 0, 21)) + + case 0: /*Zero*/ + case 1: /*One*/ + case 2: /*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4: /*four*/ + return "hello"; + case 5: /*five*/ + default: /*six*/ + return "world"; + } + +} diff --git a/tests/baselines/reference/commentsAfterCaseClauses3.types b/tests/baselines/reference/commentsAfterCaseClauses3.types new file mode 100644 index 00000000000..556370f4395 --- /dev/null +++ b/tests/baselines/reference/commentsAfterCaseClauses3.types @@ -0,0 +1,39 @@ +=== tests/cases/compiler/commentsAfterCaseClauses3.ts === +function getSecurity(level) { +>getSecurity : (level: any) => "Hi" | "hello" | "world" +>level : any + + switch(level){ +>level : any + + case 0: /*Zero*/ +>0 : 0 + + case 1: /*One*/ +>1 : 1 + + case 2: /*two*/ +>2 : 2 + + // Leading comments + return "Hi"; +>"Hi" : "Hi" + + case 3: /*three*/ +>3 : 3 + + case 4: /*four*/ +>4 : 4 + + return "hello"; +>"hello" : "hello" + + case 5: /*five*/ +>5 : 5 + + default: /*six*/ + return "world"; +>"world" : "world" + } + +} diff --git a/tests/baselines/reference/parserRealSource1.js b/tests/baselines/reference/parserRealSource1.js index d26e749a667..e41cb2a4b3f 100644 --- a/tests/baselines/reference/parserRealSource1.js +++ b/tests/baselines/reference/parserRealSource1.js @@ -247,28 +247,28 @@ var TypeScript; var addChar = function (index) { var ch = value.charCodeAt(index); switch (ch) { - case 0x09: + case 0x09:// tab result += "\\t"; break; - case 0x0a: + case 0x0a:// line feed result += "\\n"; break; - case 0x0b: + case 0x0b:// vertical tab result += "\\v"; break; - case 0x0c: + case 0x0c:// form feed result += "\\f"; break; - case 0x0d: + case 0x0d:// carriage return result += "\\r"; break; - case 0x22: + case 0x22:// double quote result += "\\\""; break; - case 0x27: + case 0x27:// single quote result += "\\\'"; break; - case 0x5c: + case 0x5c:// Backslash result += "\\"; break; default: diff --git a/tests/baselines/reference/parserindenter.js b/tests/baselines/reference/parserindenter.js index 8beb2393748..17f71318940 100644 --- a/tests/baselines/reference/parserindenter.js +++ b/tests/baselines/reference/parserindenter.js @@ -912,20 +912,20 @@ var Formatting; Indenter.prototype.GetSpecialCaseIndentation = function (token, node) { var indentationInfo = null; switch (token.Token) { - case AuthorTokenKind.atkLCurly: + case AuthorTokenKind.atkLCurly:// { is not part of the tree indentationInfo = this.GetSpecialCaseIndentationForLCurly(node); return indentationInfo; case AuthorTokenKind.atkElse: // else is not part of the tree - case AuthorTokenKind.atkRBrack: + case AuthorTokenKind.atkRBrack:// ] is not part of the tree indentationInfo = node.GetNodeStartLineIndentation(this); return indentationInfo; - case AuthorTokenKind.atkRCurly: + case AuthorTokenKind.atkRCurly:// } is not part of the tree // if '}' is for a body-block, get indentation based on its parent. if (node.AuthorNode.Details.Kind == AuthorParseNodeKind.apnkBlock && node.AuthorNode.EdgeLabel == AuthorParseNodeEdge.apneBody) node = node.Parent; indentationInfo = node.GetNodeStartLineIndentation(this); return indentationInfo; - case AuthorTokenKind.atkWhile: + case AuthorTokenKind.atkWhile:// while (in do-while) is not part of the tree if (node.AuthorNode.Details.Kind == AuthorParseNodeKind.apnkDoWhile) { indentationInfo = node.GetNodeStartLineIndentation(this); return indentationInfo; diff --git a/tests/baselines/reference/switchStatementsWithMultipleDefaults.js b/tests/baselines/reference/switchStatementsWithMultipleDefaults.js index e65e10a0c99..e41d8c016ef 100644 --- a/tests/baselines/reference/switchStatementsWithMultipleDefaults.js +++ b/tests/baselines/reference/switchStatementsWithMultipleDefaults.js @@ -35,7 +35,7 @@ var x = 10; switch (x) { case 1: case 2: - default: + default:// No issues. break; default: // Error; second 'default' clause. default: // Error; third 'default' clause. @@ -43,12 +43,12 @@ switch (x) { x *= x; } switch (x) { - default: + default:// No issues. break; case 100: switch (x * x) { default: // No issues. - default: + default:// Error; second 'default' clause. break; case 10000: x /= x; diff --git a/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js b/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js index 2d52dd761cc..d733ce38a7b 100644 --- a/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js +++ b/tests/baselines/reference/switchStatementsWithMultipleDefaults1.js @@ -17,7 +17,7 @@ var x = 10; switch (x) { case 1: case 2: - default: + default:// No issues. break; default: // Error; second 'default' clause. default: // Error; third 'default' clause. diff --git a/tests/cases/compiler/commentsAfterCaseClauses1.ts b/tests/cases/compiler/commentsAfterCaseClauses1.ts new file mode 100644 index 00000000000..8b494161584 --- /dev/null +++ b/tests/cases/compiler/commentsAfterCaseClauses1.ts @@ -0,0 +1,14 @@ +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + return "Hi"; + case 3: // three + case 4 : // four + return "hello"; + case 5: // five + default: // default + return "world"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/commentsAfterCaseClauses2.ts b/tests/cases/compiler/commentsAfterCaseClauses2.ts new file mode 100644 index 00000000000..9c35b80894e --- /dev/null +++ b/tests/cases/compiler/commentsAfterCaseClauses2.ts @@ -0,0 +1,17 @@ +function getSecurity(level) { + switch(level){ + case 0: // Zero + case 1: // one + case 2: // two + // Leading comments + return "Hi"; + case 3: // three + case 4: // four + return "hello"; + case 5: // five + default: // default + return "world"; + // Comment After + } /*Comment 1*/ // Comment After 1 + // Comment After 2 +} \ No newline at end of file diff --git a/tests/cases/compiler/commentsAfterCaseClauses3.ts b/tests/cases/compiler/commentsAfterCaseClauses3.ts new file mode 100644 index 00000000000..894e743c2e7 --- /dev/null +++ b/tests/cases/compiler/commentsAfterCaseClauses3.ts @@ -0,0 +1,16 @@ +function getSecurity(level) { + switch(level){ + case 0: /*Zero*/ + case 1: /*One*/ + case 2: /*two*/ + // Leading comments + return "Hi"; + case 3: /*three*/ + case 4: /*four*/ + return "hello"; + case 5: /*five*/ + default: /*six*/ + return "world"; + } + +} \ No newline at end of file From 1c3cdf11b52564d7ee507e12a43588f2a279a1ca Mon Sep 17 00:00:00 2001 From: Yui Date: Tue, 23 May 2017 10:26:07 -0700 Subject: [PATCH 270/282] Fix the issue 15232 (#16004) --- src/compiler/comments.ts | 6 +- .../commentEmittingInPreserveJsx1.js | 57 +++++++++++++++++++ .../commentEmittingInPreserveJsx1.symbols | 45 +++++++++++++++ .../commentEmittingInPreserveJsx1.types | 51 +++++++++++++++++ .../jsx/commentEmittingInPreserveJsx1.tsx | 35 ++++++++++++ 5 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/commentEmittingInPreserveJsx1.js create mode 100644 tests/baselines/reference/commentEmittingInPreserveJsx1.symbols create mode 100644 tests/baselines/reference/commentEmittingInPreserveJsx1.types create mode 100644 tests/cases/conformance/jsx/commentEmittingInPreserveJsx1.tsx diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts index c50cacc2ccb..06285309f64 100644 --- a/src/compiler/comments.ts +++ b/src/compiler/comments.ts @@ -58,8 +58,10 @@ namespace ts { } const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement; - const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0; - const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0; + // 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. + const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0 || node.kind === SyntaxKind.JsxText; + const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0 || node.kind === SyntaxKind.JsxText; // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. diff --git a/tests/baselines/reference/commentEmittingInPreserveJsx1.js b/tests/baselines/reference/commentEmittingInPreserveJsx1.js new file mode 100644 index 00000000000..45e2148e007 --- /dev/null +++ b/tests/baselines/reference/commentEmittingInPreserveJsx1.js @@ -0,0 +1,57 @@ +//// [file.tsx] +import React = require('react'); + +
+ // Not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + "Hi" + } + // Another not Comment +
; + +
+ /* Not Comment */ + { + //Comment just Fine + "Hi" + } +
; + +//// [file.jsx] +"use strict"; +exports.__esModule = true; +var React = require("react"); +
+ // Not Comment +
; +
+ // Not Comment + + // Another not Comment +
; +
+ // Not Comment + { +//Comment just Fine +"Hi"} + // Another not Comment +
; +
+ /* Not Comment */ + { +//Comment just Fine +"Hi"} +
; diff --git a/tests/baselines/reference/commentEmittingInPreserveJsx1.symbols b/tests/baselines/reference/commentEmittingInPreserveJsx1.symbols new file mode 100644 index 00000000000..43d833e27b1 --- /dev/null +++ b/tests/baselines/reference/commentEmittingInPreserveJsx1.symbols @@ -0,0 +1,45 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + // Not Comment +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + // Not Comment + { + //Comment just Fine + "Hi" + } + // Another not Comment +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + + /* Not Comment */ + { + //Comment just Fine + "Hi" + } +
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + diff --git a/tests/baselines/reference/commentEmittingInPreserveJsx1.types b/tests/baselines/reference/commentEmittingInPreserveJsx1.types new file mode 100644 index 00000000000..2e968033d4c --- /dev/null +++ b/tests/baselines/reference/commentEmittingInPreserveJsx1.types @@ -0,0 +1,51 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +
+>
// Not Comment
: JSX.Element +>div : any + + // Not Comment +
; +>div : any + +
+>
// Not Comment { //Comment just Fine } // Another not Comment
: JSX.Element +>div : any + + // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; +>div : any + +
+>
// Not Comment { //Comment just Fine "Hi" } // Another not Comment
: JSX.Element +>div : any + + // Not Comment + { + //Comment just Fine + "Hi" +>"Hi" : "Hi" + } + // Another not Comment +
; +>div : any + +
+>
/* Not Comment */ { //Comment just Fine "Hi" }
: JSX.Element +>div : any + + /* Not Comment */ + { + //Comment just Fine + "Hi" +>"Hi" : "Hi" + } +
; +>div : any + diff --git a/tests/cases/conformance/jsx/commentEmittingInPreserveJsx1.tsx b/tests/cases/conformance/jsx/commentEmittingInPreserveJsx1.tsx new file mode 100644 index 00000000000..323cd029189 --- /dev/null +++ b/tests/cases/conformance/jsx/commentEmittingInPreserveJsx1.tsx @@ -0,0 +1,35 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +
+ // Not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + } + // Another not Comment +
; + +
+ // Not Comment + { + //Comment just Fine + "Hi" + } + // Another not Comment +
; + +
+ /* Not Comment */ + { + //Comment just Fine + "Hi" + } +
; \ No newline at end of file From 49638ab2eb2c9674b52660ab46009249e2f3a7dc Mon Sep 17 00:00:00 2001 From: Ika Date: Wed, 24 May 2017 01:37:21 +0800 Subject: [PATCH 271/282] Add missing questionToken in emitMethod/PropertyDeclaration (#16020) --- src/compiler/emitter.ts | 2 ++ src/harness/unittests/printer.ts | 32 +++++++++++++++++++ ...ctly.classWithOptionalMethodAndProperty.js | 4 +++ 3 files changed, 38 insertions(+) create mode 100644 tests/baselines/reference/printerApi/printsNodeCorrectly.classWithOptionalMethodAndProperty.js diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index c0b0d170de8..0cbb961e9f7 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -860,6 +860,7 @@ namespace ts { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -881,6 +882,7 @@ namespace ts { emitModifiers(node, node.modifiers); writeIfPresent(node.asteriskToken, "*"); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitSignatureAndBody(node, emitSignatureHead); } diff --git a/src/harness/unittests/printer.ts b/src/harness/unittests/printer.ts index 0c6d4bfe8f7..aedaacbf76c 100644 --- a/src/harness/unittests/printer.ts +++ b/src/harness/unittests/printer.ts @@ -98,8 +98,40 @@ namespace ts { ) ]) ); + + // https://github.com/Microsoft/TypeScript/issues/15971 + const classWithOptionalMethodAndProperty = createClassDeclaration( + undefined, + /* modifiers */ createNodeArray([createToken(SyntaxKind.DeclareKeyword)]), + /* name */ createIdentifier("X"), + undefined, + undefined, + createNodeArray([ + createMethod( + undefined, + undefined, + undefined, + /* name */ createIdentifier("method"), + /* questionToken */ createToken(SyntaxKind.QuestionToken), + undefined, + undefined, + /* type */ createKeywordTypeNode(SyntaxKind.VoidKeyword), + undefined + ), + createProperty( + undefined, + undefined, + /* name */ createIdentifier("property"), + /* questionToken */ createToken(SyntaxKind.QuestionToken), + /* type */ createKeywordTypeNode(SyntaxKind.StringKeyword), + undefined + ), + ]) + ); + // tslint:enable boolean-trivia printsCorrectly("class", {}, printer => printer.printNode(EmitHint.Unspecified, syntheticNode, sourceFile)); + printsCorrectly("classWithOptionalMethodAndProperty", {}, printer => printer.printNode(EmitHint.Unspecified, classWithOptionalMethodAndProperty, sourceFile)); }); }); } diff --git a/tests/baselines/reference/printerApi/printsNodeCorrectly.classWithOptionalMethodAndProperty.js b/tests/baselines/reference/printerApi/printsNodeCorrectly.classWithOptionalMethodAndProperty.js new file mode 100644 index 00000000000..6626f2e35c9 --- /dev/null +++ b/tests/baselines/reference/printerApi/printsNodeCorrectly.classWithOptionalMethodAndProperty.js @@ -0,0 +1,4 @@ +declare class X { + method?(): void; + property?: string; +} \ No newline at end of file From e4d6752a932c680d67bf3982393a3276819d9cd7 Mon Sep 17 00:00:00 2001 From: Donald Pipowitch Date: Tue, 23 May 2017 19:40:46 +0200 Subject: [PATCH 272/282] add `createProgram` docs (#15697) * add `createProgram` docs * updated `createProgram` docs --- src/compiler/program.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index dae49832183..dd293727b4a 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -386,6 +386,19 @@ namespace ts { allDiagnostics?: Diagnostic[]; } + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param rootNames - A set of root files. + * @param options - The compiler options which should be used. + * @param host - The host interacts with the underlying file system. + * @param oldProgram - Reuses an old program structure. + * @returns A 'Program' object. + */ export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program { let program: Program; let files: SourceFile[] = []; From f9a1fca38810823654315f0a90c969e76b6d7bfc Mon Sep 17 00:00:00 2001 From: Ika Date: Wed, 24 May 2017 02:07:34 +0800 Subject: [PATCH 273/282] Add missing emitter for NamespaceExportDeclaration (#16025) --- src/compiler/binder.ts | 1 + src/compiler/emitter.ts | 8 ++++++++ src/compiler/transformers/ts.ts | 3 +++ src/harness/unittests/printer.ts | 3 +++ .../printsNodeCorrectly.namespaceExportDeclaration.js | 1 + 5 files changed, 16 insertions(+) create mode 100644 tests/baselines/reference/printerApi/printsNodeCorrectly.namespaceExportDeclaration.js diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 30e2b7781f6..204a979d928 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -3398,6 +3398,7 @@ namespace ts { case SyntaxKind.IndexedAccessType: case SyntaxKind.MappedType: case SyntaxKind.LiteralType: + case SyntaxKind.NamespaceExportDeclaration: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = TransformFlags.AssertTypeScript; excludeFlags = TransformFlags.TypeExcludes; diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 0cbb961e9f7..e00d46fe94e 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -571,6 +571,8 @@ namespace ts { return emitModuleBlock(node); case SyntaxKind.CaseBlock: return emitCaseBlock(node); + case SyntaxKind.NamespaceExportDeclaration: + return emitNamespaceExportDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: return emitImportEqualsDeclaration(node); case SyntaxKind.ImportDeclaration: @@ -1886,6 +1888,12 @@ namespace ts { write(";"); } + function emitNamespaceExportDeclaration(node: NamespaceExportDeclaration) { + write("export as namespace "); + emit(node.name); + write(";"); + } + function emitNamedExports(node: NamedExports) { emitNamedImportsOrExports(node); } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index cc7f89acfb8..d02aaecf333 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -345,6 +345,9 @@ namespace ts { case SyntaxKind.PropertyDeclaration: // TypeScript property declarations are elided. + + case SyntaxKind.NamespaceExportDeclaration: + // TypeScript namespace export declarations are elided. return undefined; case SyntaxKind.Constructor: diff --git a/src/harness/unittests/printer.ts b/src/harness/unittests/printer.ts index aedaacbf76c..a9af46b2780 100644 --- a/src/harness/unittests/printer.ts +++ b/src/harness/unittests/printer.ts @@ -131,6 +131,9 @@ namespace ts { // tslint:enable boolean-trivia printsCorrectly("class", {}, printer => printer.printNode(EmitHint.Unspecified, syntheticNode, sourceFile)); + + printsCorrectly("namespaceExportDeclaration", {}, printer => printer.printNode(EmitHint.Unspecified, createNamespaceExportDeclaration("B"), sourceFile)); + printsCorrectly("classWithOptionalMethodAndProperty", {}, printer => printer.printNode(EmitHint.Unspecified, classWithOptionalMethodAndProperty, sourceFile)); }); }); diff --git a/tests/baselines/reference/printerApi/printsNodeCorrectly.namespaceExportDeclaration.js b/tests/baselines/reference/printerApi/printsNodeCorrectly.namespaceExportDeclaration.js new file mode 100644 index 00000000000..725da0cef9f --- /dev/null +++ b/tests/baselines/reference/printerApi/printsNodeCorrectly.namespaceExportDeclaration.js @@ -0,0 +1 @@ +export as namespace B; \ No newline at end of file From 5ef6192c20c051d3b03bc0059b7a1e0a86163379 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 23 May 2017 13:40:03 -0700 Subject: [PATCH 274/282] Allow export default interface. Related to issue 3792. (#16040) * Allow export default interface. Related to issue 3792. * Update exportDefaultAbstractClass test * Allow default export to be a non-value for lookup purposes * Add local usage to exportDefaultInterface test --- src/compiler/parser.ts | 7 +-- src/compiler/utilities.ts | 4 +- .../reference/exportDefaultAbstractClass.js | 48 +++++++++++++++++-- .../exportDefaultAbstractClass.symbols | 27 ++++++++++- .../exportDefaultAbstractClass.types | 31 +++++++++++- .../reference/exportDefaultInterface.js | 24 ++++++++++ .../reference/exportDefaultInterface.symbols | 31 ++++++++++++ .../reference/exportDefaultInterface.types | 33 +++++++++++++ .../compiler/exportDefaultAbstractClass.ts | 16 +++++-- .../cases/compiler/exportDefaultInterface.ts | 11 +++++ 10 files changed, 215 insertions(+), 17 deletions(-) create mode 100644 tests/baselines/reference/exportDefaultInterface.js create mode 100644 tests/baselines/reference/exportDefaultInterface.symbols create mode 100644 tests/baselines/reference/exportDefaultInterface.types create mode 100644 tests/cases/compiler/exportDefaultInterface.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 87bd36ee3a0..04209ab0924 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1240,12 +1240,12 @@ namespace ts { if (token() === SyntaxKind.ExportKeyword) { nextToken(); if (token() === SyntaxKind.DefaultKeyword) { - return lookAhead(nextTokenIsClassOrFunctionOrAsync); + return lookAhead(nextTokenCanFollowDefaultKeyword); } return token() !== SyntaxKind.AsteriskToken && token() !== SyntaxKind.AsKeyword && token() !== SyntaxKind.OpenBraceToken && canFollowModifier(); } if (token() === SyntaxKind.DefaultKeyword) { - return nextTokenIsClassOrFunctionOrAsync(); + return nextTokenCanFollowDefaultKeyword(); } if (token() === SyntaxKind.StaticKeyword) { nextToken(); @@ -1267,9 +1267,10 @@ namespace ts { || isLiteralPropertyName(); } - function nextTokenIsClassOrFunctionOrAsync(): boolean { + function nextTokenCanFollowDefaultKeyword(): boolean { nextToken(); return token() === SyntaxKind.ClassKeyword || token() === SyntaxKind.FunctionKeyword || + token() === SyntaxKind.InterfaceKeyword || (token() === SyntaxKind.AbstractKeyword && lookAhead(nextTokenIsClassKeywordOnSameLine)) || (token() === SyntaxKind.AsyncKeyword && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 3a8b8b59f7d..22210419af7 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3168,11 +3168,11 @@ namespace ts { } export function getLocalSymbolForExportDefault(symbol: Symbol) { - return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined; + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; } function isExportDefaultSymbol(symbol: Symbol): boolean { - return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, ModifierFlags.Default); + return symbol && length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], ModifierFlags.Default); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ diff --git a/tests/baselines/reference/exportDefaultAbstractClass.js b/tests/baselines/reference/exportDefaultAbstractClass.js index c8dba03543d..38976311d63 100644 --- a/tests/baselines/reference/exportDefaultAbstractClass.js +++ b/tests/baselines/reference/exportDefaultAbstractClass.js @@ -1,14 +1,29 @@ //// [tests/cases/compiler/exportDefaultAbstractClass.ts] //// //// [a.ts] -export default abstract class A {} +export default abstract class A { a: number; } + +class B extends A {} +new B().a.toExponential(); //// [b.ts] -import A from './a' - +import A from './a'; + +class C extends A {} +new C().a.toExponential(); //// [a.js] "use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); exports.__esModule = true; var A = (function () { function A() { @@ -16,6 +31,33 @@ var A = (function () { return A; }()); exports["default"] = A; +var B = (function (_super) { + __extends(B, _super); + function B() { + return _super !== null && _super.apply(this, arguments) || this; + } + return B; +}(A)); +new B().a.toExponential(); //// [b.js] "use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); exports.__esModule = true; +var a_1 = require("./a"); +var C = (function (_super) { + __extends(C, _super); + function C() { + return _super !== null && _super.apply(this, arguments) || this; + } + return C; +}(a_1["default"])); +new C().a.toExponential(); diff --git a/tests/baselines/reference/exportDefaultAbstractClass.symbols b/tests/baselines/reference/exportDefaultAbstractClass.symbols index 75c6c068f08..27e42487f31 100644 --- a/tests/baselines/reference/exportDefaultAbstractClass.symbols +++ b/tests/baselines/reference/exportDefaultAbstractClass.symbols @@ -1,8 +1,31 @@ === tests/cases/compiler/a.ts === -export default abstract class A {} +export default abstract class A { a: number; } +>A : Symbol(A, Decl(a.ts, 0, 0)) +>a : Symbol(A.a, Decl(a.ts, 0, 33)) + +class B extends A {} +>B : Symbol(B, Decl(a.ts, 0, 46)) >A : Symbol(A, Decl(a.ts, 0, 0)) +new B().a.toExponential(); +>new B().a.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>new B().a : Symbol(A.a, Decl(a.ts, 0, 33)) +>B : Symbol(B, Decl(a.ts, 0, 46)) +>a : Symbol(A.a, Decl(a.ts, 0, 33)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + === tests/cases/compiler/b.ts === -import A from './a' +import A from './a'; >A : Symbol(A, Decl(b.ts, 0, 6)) +class C extends A {} +>C : Symbol(C, Decl(b.ts, 0, 20)) +>A : Symbol(A, Decl(b.ts, 0, 6)) + +new C().a.toExponential(); +>new C().a.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>new C().a : Symbol(A.a, Decl(a.ts, 0, 33)) +>C : Symbol(C, Decl(b.ts, 0, 20)) +>a : Symbol(A.a, Decl(a.ts, 0, 33)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + diff --git a/tests/baselines/reference/exportDefaultAbstractClass.types b/tests/baselines/reference/exportDefaultAbstractClass.types index d400be1af43..776ad01420a 100644 --- a/tests/baselines/reference/exportDefaultAbstractClass.types +++ b/tests/baselines/reference/exportDefaultAbstractClass.types @@ -1,8 +1,35 @@ === tests/cases/compiler/a.ts === -export default abstract class A {} +export default abstract class A { a: number; } +>A : A +>a : number + +class B extends A {} +>B : B >A : A +new B().a.toExponential(); +>new B().a.toExponential() : string +>new B().a.toExponential : (fractionDigits?: number) => string +>new B().a : number +>new B() : B +>B : typeof B +>a : number +>toExponential : (fractionDigits?: number) => string + === tests/cases/compiler/b.ts === -import A from './a' +import A from './a'; >A : typeof A +class C extends A {} +>C : C +>A : A + +new C().a.toExponential(); +>new C().a.toExponential() : string +>new C().a.toExponential : (fractionDigits?: number) => string +>new C().a : number +>new C() : C +>C : typeof C +>a : number +>toExponential : (fractionDigits?: number) => string + diff --git a/tests/baselines/reference/exportDefaultInterface.js b/tests/baselines/reference/exportDefaultInterface.js new file mode 100644 index 00000000000..e7b5c945e32 --- /dev/null +++ b/tests/baselines/reference/exportDefaultInterface.js @@ -0,0 +1,24 @@ +//// [tests/cases/compiler/exportDefaultInterface.ts] //// + +//// [a.ts] +export default interface A { value: number; } + +var a: A; +a.value.toExponential(); + +//// [b.ts] +import A from './a'; + +var a: A; +a.value.toExponential(); + +//// [a.js] +"use strict"; +exports.__esModule = true; +var a; +a.value.toExponential(); +//// [b.js] +"use strict"; +exports.__esModule = true; +var a; +a.value.toExponential(); diff --git a/tests/baselines/reference/exportDefaultInterface.symbols b/tests/baselines/reference/exportDefaultInterface.symbols new file mode 100644 index 00000000000..1a3b172fe97 --- /dev/null +++ b/tests/baselines/reference/exportDefaultInterface.symbols @@ -0,0 +1,31 @@ +=== tests/cases/compiler/a.ts === +export default interface A { value: number; } +>A : Symbol(A, Decl(a.ts, 0, 0)) +>value : Symbol(A.value, Decl(a.ts, 0, 28)) + +var a: A; +>a : Symbol(a, Decl(a.ts, 2, 3)) +>A : Symbol(A, Decl(a.ts, 0, 0)) + +a.value.toExponential(); +>a.value.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>a.value : Symbol(A.value, Decl(a.ts, 0, 28)) +>a : Symbol(a, Decl(a.ts, 2, 3)) +>value : Symbol(A.value, Decl(a.ts, 0, 28)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + +=== tests/cases/compiler/b.ts === +import A from './a'; +>A : Symbol(A, Decl(b.ts, 0, 6)) + +var a: A; +>a : Symbol(a, Decl(b.ts, 2, 3)) +>A : Symbol(A, Decl(b.ts, 0, 6)) + +a.value.toExponential(); +>a.value.toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) +>a.value : Symbol(A.value, Decl(a.ts, 0, 28)) +>a : Symbol(a, Decl(b.ts, 2, 3)) +>value : Symbol(A.value, Decl(a.ts, 0, 28)) +>toExponential : Symbol(Number.toExponential, Decl(lib.d.ts, --, --)) + diff --git a/tests/baselines/reference/exportDefaultInterface.types b/tests/baselines/reference/exportDefaultInterface.types new file mode 100644 index 00000000000..636197339f4 --- /dev/null +++ b/tests/baselines/reference/exportDefaultInterface.types @@ -0,0 +1,33 @@ +=== tests/cases/compiler/a.ts === +export default interface A { value: number; } +>A : A +>value : number + +var a: A; +>a : A +>A : A + +a.value.toExponential(); +>a.value.toExponential() : string +>a.value.toExponential : (fractionDigits?: number) => string +>a.value : number +>a : A +>value : number +>toExponential : (fractionDigits?: number) => string + +=== tests/cases/compiler/b.ts === +import A from './a'; +>A : any + +var a: A; +>a : A +>A : A + +a.value.toExponential(); +>a.value.toExponential() : string +>a.value.toExponential : (fractionDigits?: number) => string +>a.value : number +>a : A +>value : number +>toExponential : (fractionDigits?: number) => string + diff --git a/tests/cases/compiler/exportDefaultAbstractClass.ts b/tests/cases/compiler/exportDefaultAbstractClass.ts index 584e95b6b03..31877911622 100644 --- a/tests/cases/compiler/exportDefaultAbstractClass.ts +++ b/tests/cases/compiler/exportDefaultAbstractClass.ts @@ -1,5 +1,11 @@ -// @filename: a.ts -export default abstract class A {} - -// @filename: b.ts -import A from './a' +// @Filename: a.ts +export default abstract class A { a: number; } + +class B extends A {} +new B().a.toExponential(); + +// @Filename: b.ts +import A from './a'; + +class C extends A {} +new C().a.toExponential(); \ No newline at end of file diff --git a/tests/cases/compiler/exportDefaultInterface.ts b/tests/cases/compiler/exportDefaultInterface.ts new file mode 100644 index 00000000000..c7bbbe8019e --- /dev/null +++ b/tests/cases/compiler/exportDefaultInterface.ts @@ -0,0 +1,11 @@ +// @Filename: a.ts +export default interface A { value: number; } + +var a: A; +a.value.toExponential(); + +// @Filename: b.ts +import A from './a'; + +var a: A; +a.value.toExponential(); \ No newline at end of file From 2f65b2c160c3abe13271682d8b1bff525de93438 Mon Sep 17 00:00:00 2001 From: Herrington Darkholme Date: Wed, 24 May 2017 05:13:32 +0800 Subject: [PATCH 275/282] fix #11463, null assertion block uninitialized error (#14020) --- src/compiler/checker.ts | 1 + .../baselines/reference/typeGuardsAsAssertions.js | 9 +++++++++ .../reference/typeGuardsAsAssertions.symbols | 12 ++++++++++++ .../reference/typeGuardsAsAssertions.types | 14 ++++++++++++++ .../controlFlow/typeGuardsAsAssertions.ts | 5 +++++ 5 files changed, 41 insertions(+) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 07c20ad7aa0..ce982a113f2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12035,6 +12035,7 @@ namespace ts { // declaration container are the same). const assumeInitialized = isParameter || isOuterVariable || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0 || isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || + node.parent.kind === SyntaxKind.NonNullExpression || isInAmbientContext(declaration); const initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, getRootDeclaration(declaration) as VariableLikeDeclaration) : type) : type === autoType || type === autoArrayType ? undefinedType : diff --git a/tests/baselines/reference/typeGuardsAsAssertions.js b/tests/baselines/reference/typeGuardsAsAssertions.js index 8c9b2048514..692af453c0c 100644 --- a/tests/baselines/reference/typeGuardsAsAssertions.js +++ b/tests/baselines/reference/typeGuardsAsAssertions.js @@ -119,6 +119,11 @@ function f6() { x = ""; x!.slice(); } + +function f7() { + let x: string; + x!.slice(); +} //// [typeGuardsAsAssertions.js] @@ -227,3 +232,7 @@ function f6() { x = ""; x.slice(); } +function f7() { + var x; + x.slice(); +} diff --git a/tests/baselines/reference/typeGuardsAsAssertions.symbols b/tests/baselines/reference/typeGuardsAsAssertions.symbols index 71c02412a12..346418871db 100644 --- a/tests/baselines/reference/typeGuardsAsAssertions.symbols +++ b/tests/baselines/reference/typeGuardsAsAssertions.symbols @@ -312,3 +312,15 @@ function f6() { >slice : Symbol(String.slice, Decl(lib.d.ts, --, --)) } +function f7() { +>f7 : Symbol(f7, Decl(typeGuardsAsAssertions.ts, 119, 1)) + + let x: string; +>x : Symbol(x, Decl(typeGuardsAsAssertions.ts, 122, 7)) + + x!.slice(); +>x!.slice : Symbol(String.slice, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(typeGuardsAsAssertions.ts, 122, 7)) +>slice : Symbol(String.slice, Decl(lib.d.ts, --, --)) +} + diff --git a/tests/baselines/reference/typeGuardsAsAssertions.types b/tests/baselines/reference/typeGuardsAsAssertions.types index 09378bcee54..bd11b4a6f20 100644 --- a/tests/baselines/reference/typeGuardsAsAssertions.types +++ b/tests/baselines/reference/typeGuardsAsAssertions.types @@ -382,3 +382,17 @@ function f6() { >slice : (start?: number | undefined, end?: number | undefined) => string } +function f7() { +>f7 : () => void + + let x: string; +>x : string + + x!.slice(); +>x!.slice() : string +>x!.slice : (start?: number | undefined, end?: number | undefined) => string +>x! : string +>x : string +>slice : (start?: number | undefined, end?: number | undefined) => string +} + diff --git a/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts b/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts index 912eaa64e80..5ce430bc19a 100644 --- a/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts +++ b/tests/cases/conformance/controlFlow/typeGuardsAsAssertions.ts @@ -120,3 +120,8 @@ function f6() { x = ""; x!.slice(); } + +function f7() { + let x: string; + x!.slice(); +} From b4ee6b19aac530a208ea2d448b83fbcb61e0f4b7 Mon Sep 17 00:00:00 2001 From: Arthur Ozga Date: Tue, 23 May 2017 14:22:01 -0700 Subject: [PATCH 276/282] Object literal formatting (#16007) * consolidate object literal formatting * accept baselines --- src/compiler/emitter.ts | 5 +- .../reference/arrowFunctionExpressions.types | 20 +++---- .../contextuallyTypedBindingInitializer.types | 12 ++-- ...uallyTypedBindingInitializerNegative.types | 12 ++-- .../reference/contextuallyTypedIife.types | 16 ++--- .../controlFlowDestructuringParameters.types | 2 +- .../declarationEmitBindingPatterns.types | 6 +- .../declarationEmitDestructuring1.types | 4 +- ...OptionalBindingParametersInOverloads.types | 4 +- .../destructureOptionalParameter.types | 4 +- ...tructuringParameterDeclaration2.errors.txt | 4 +- ...estructuringParameterDeclaration7ES5.types | 4 +- ...ringParameterDeclaration7ES5iterable.types | 4 +- .../destructuringWithGenericParameter.types | 2 +- ...destructuringWithLiteralInitializers.types | 58 +++++++++---------- .../reference/emitArrowFunctionES6.types | 20 +++---- ...ableDeclarationBindingPatterns01_ES5.types | 4 +- ...arationBindingPatterns01_ES5iterable.types | 4 +- ...ableDeclarationBindingPatterns01_ES6.types | 4 +- ...backToBindingPatternForTypeInference.types | 8 +-- ...licitAnyDestructuringInPrivateMethod.types | 4 +- tests/baselines/reference/objectRest.types | 4 +- .../reference/objectRestParameter.types | 16 ++--- .../reference/objectRestParameterES5.types | 16 ++--- ...erInitializerBeforeDestructuringEmit.types | 2 +- ...gParameterNestedObjectBindingPattern.types | 18 +++--- ...tedObjectBindingPatternDefaultValues.types | 18 +++--- ...cturingParameterObjectBindingPattern.types | 18 +++--- ...terObjectBindingPatternDefaultValues.types | 18 +++--- .../tsxSpreadAttributesResolution13.types | 6 +- .../tsxSpreadAttributesResolution15.types | 4 +- .../reference/tsxSpreadChildren.types | 4 +- ...xStatelessFunctionComponentOverload1.types | 18 +++--- .../tsxStatelessFunctionComponents3.types | 2 +- 34 files changed, 172 insertions(+), 173 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index e00d46fe94e..aef1a61e080 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1064,7 +1064,7 @@ namespace ts { } else { write("{"); - emitList(node, elements, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.ObjectBindingPatternElements : ListFormat.ObjectBindingPatternElementsWithSpaceBetweenBraces); + emitList(node, elements, ListFormat.ObjectBindingPatternElements); write("}"); } } @@ -3019,8 +3019,7 @@ namespace ts { TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, - ObjectBindingPatternElements = SingleLine | CommaDelimited | SpaceBetweenSiblings, - ObjectBindingPatternElementsWithSpaceBetweenBraces = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings, + ObjectBindingPatternElements = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings, ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings, ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces, ArrayLiteralExpressionElements = PreserveLines | CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | Indented | SquareBrackets, diff --git a/tests/baselines/reference/arrowFunctionExpressions.types b/tests/baselines/reference/arrowFunctionExpressions.types index aad43240daa..0de6c674d18 100644 --- a/tests/baselines/reference/arrowFunctionExpressions.types +++ b/tests/baselines/reference/arrowFunctionExpressions.types @@ -83,25 +83,25 @@ var p5 = ([a = 1]) => { }; >1 : 1 var p6 = ({ a }) => { }; ->p6 : ({a}: { a: any; }) => void ->({ a }) => { } : ({a}: { a: any; }) => void +>p6 : ({ a }: { a: any; }) => void +>({ a }) => { } : ({ a }: { a: any; }) => void >a : any var p7 = ({ a: { b } }) => { }; ->p7 : ({a: {b}}: { a: { b: any; }; }) => void ->({ a: { b } }) => { } : ({a: {b}}: { a: { b: any; }; }) => void +>p7 : ({ a: { b } }: { a: { b: any; }; }) => void +>({ a: { b } }) => { } : ({ a: { b } }: { a: { b: any; }; }) => void >a : any >b : any var p8 = ({ a = 1 }) => { }; ->p8 : ({a}: { a?: number; }) => void ->({ a = 1 }) => { } : ({a}: { a?: number; }) => void +>p8 : ({ a }: { a?: number; }) => void +>({ a = 1 }) => { } : ({ a }: { a?: number; }) => void >a : number >1 : 1 var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; ->p9 : ({a: {b}}: { a?: { b?: number; }; }) => void ->({ a: { b = 1 } = { b: 1 } }) => { } : ({a: {b}}: { a?: { b?: number; }; }) => void +>p9 : ({ a: { b } }: { a?: { b?: number; }; }) => void +>({ a: { b = 1 } = { b: 1 } }) => { } : ({ a: { b } }: { a?: { b?: number; }; }) => void >a : any >b : number >1 : 1 @@ -110,8 +110,8 @@ var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; >1 : 1 var p10 = ([{ value, done }]) => { }; ->p10 : ([{value, done}]: [{ value: any; done: any; }]) => void ->([{ value, done }]) => { } : ([{value, done}]: [{ value: any; done: any; }]) => void +>p10 : ([{ value, done }]: [{ value: any; done: any; }]) => void +>([{ value, done }]) => { } : ([{ value, done }]: [{ value: any; done: any; }]) => void >value : any >done : any diff --git a/tests/baselines/reference/contextuallyTypedBindingInitializer.types b/tests/baselines/reference/contextuallyTypedBindingInitializer.types index e9624b156c7..4efd22a4c84 100644 --- a/tests/baselines/reference/contextuallyTypedBindingInitializer.types +++ b/tests/baselines/reference/contextuallyTypedBindingInitializer.types @@ -7,7 +7,7 @@ interface Show { >x : number } function f({ show = v => v.toString() }: Show) {} ->f : ({show}: Show) => void +>f : ({ show }: Show) => void >show : (x: number) => string >v => v.toString() : (v: number) => string >v : number @@ -18,7 +18,7 @@ function f({ show = v => v.toString() }: Show) {} >Show : Show function f2({ "show": showRename = v => v.toString() }: Show) {} ->f2 : ({"show": showRename}: Show) => void +>f2 : ({ "show": showRename }: Show) => void >showRename : (x: number) => string >v => v.toString() : (v: number) => string >v : number @@ -29,7 +29,7 @@ function f2({ "show": showRename = v => v.toString() }: Show) {} >Show : Show function f3({ ["show"]: showRename = v => v.toString() }: Show) {} ->f3 : ({["show"]: showRename}: Show) => void +>f3 : ({ ["show"]: showRename }: Show) => void >"show" : "show" >showRename : (x: number) => string >v => v.toString() : (v: number) => string @@ -48,7 +48,7 @@ interface Nested { >Show : Show } function ff({ nested = { show: v => v.toString() } }: Nested) {} ->ff : ({nested}: Nested) => void +>ff : ({ nested }: Nested) => void >nested : Show >{ show: v => v.toString() } : { show: (v: number) => string; } >show : (v: number) => string @@ -67,7 +67,7 @@ interface Tuples { >prop : [string, number] } function g({ prop = ["hello", 1234] }: Tuples) {} ->g : ({prop}: Tuples) => void +>g : ({ prop }: Tuples) => void >prop : [string, number] >["hello", 1234] : [string, number] >"hello" : "hello" @@ -81,7 +81,7 @@ interface StringUnion { >prop : "foo" | "bar" } function h({ prop = "foo" }: StringUnion) {} ->h : ({prop}: StringUnion) => void +>h : ({ prop }: StringUnion) => void >prop : "foo" | "bar" >"foo" : "foo" >StringUnion : StringUnion diff --git a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types index 5adc82c3e62..1548e626e6d 100644 --- a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types +++ b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.types @@ -7,7 +7,7 @@ interface Show { >x : number } function f({ show: showRename = v => v }: Show) {} ->f : ({show: showRename}: Show) => void +>f : ({ show: showRename }: Show) => void >show : any >showRename : ((x: number) => string) | ((v: number) => number) >v => v : (v: number) => number @@ -16,7 +16,7 @@ function f({ show: showRename = v => v }: Show) {} >Show : Show function f2({ "show": showRename = v => v }: Show) {} ->f2 : ({"show": showRename}: Show) => void +>f2 : ({ "show": showRename }: Show) => void >showRename : ((x: number) => string) | ((v: number) => number) >v => v : (v: number) => number >v : number @@ -24,7 +24,7 @@ function f2({ "show": showRename = v => v }: Show) {} >Show : Show function f3({ ["show"]: showRename = v => v }: Show) {} ->f3 : ({["show"]: showRename}: Show) => void +>f3 : ({ ["show"]: showRename }: Show) => void >"show" : "show" >showRename : ((x: number) => string) | ((v: number) => number) >v => v : (v: number) => number @@ -40,7 +40,7 @@ interface Nested { >Show : Show } function ff({ nested: nestedRename = { show: v => v } }: Nested) {} ->ff : ({nested: nestedRename}: Nested) => void +>ff : ({ nested: nestedRename }: Nested) => void >nested : any >nestedRename : Show | { show: (v: number) => number; } >{ show: v => v } : { show: (v: number) => number; } @@ -79,7 +79,7 @@ interface Tuples { >prop : [string, number] } function g({ prop = [101, 1234] }: Tuples) {} ->g : ({prop}: Tuples) => void +>g : ({ prop }: Tuples) => void >prop : [string, number] | [number, number] >[101, 1234] : [number, number] >101 : 101 @@ -93,7 +93,7 @@ interface StringUnion { >prop : "foo" | "bar" } function h({ prop = "baz" }: StringUnion) {} ->h : ({prop}: StringUnion) => void +>h : ({ prop }: StringUnion) => void >prop : "foo" | "bar" | "baz" >"baz" : "baz" >StringUnion : StringUnion diff --git a/tests/baselines/reference/contextuallyTypedIife.types b/tests/baselines/reference/contextuallyTypedIife.types index 04ddbf50fde..77bb40df903 100644 --- a/tests/baselines/reference/contextuallyTypedIife.types +++ b/tests/baselines/reference/contextuallyTypedIife.types @@ -175,8 +175,8 @@ // destructuring parameters (with defaults too!) (({ q }) => q)({ q : 13 }); >(({ q }) => q)({ q : 13 }) : number ->(({ q }) => q) : ({q}: { q: number; }) => number ->({ q }) => q : ({q}: { q: number; }) => number +>(({ q }) => q) : ({ q }: { q: number; }) => number +>({ q }) => q : ({ q }: { q: number; }) => number >q : number >q : number >{ q : 13 } : { q: number; } @@ -185,8 +185,8 @@ (({ p = 14 }) => p)({ p : 15 }); >(({ p = 14 }) => p)({ p : 15 }) : number ->(({ p = 14 }) => p) : ({p}: { p: number; }) => number ->({ p = 14 }) => p : ({p}: { p: number; }) => number +>(({ p = 14 }) => p) : ({ p }: { p: number; }) => number +>({ p = 14 }) => p : ({ p }: { p: number; }) => number >p : number >14 : 14 >p : number @@ -196,8 +196,8 @@ (({ r = 17 } = { r: 18 }) => r)({r : 19}); >(({ r = 17 } = { r: 18 }) => r)({r : 19}) : number ->(({ r = 17 } = { r: 18 }) => r) : ({r}?: { r: number; }) => number ->({ r = 17 } = { r: 18 }) => r : ({r}?: { r: number; }) => number +>(({ r = 17 } = { r: 18 }) => r) : ({ r }?: { r: number; }) => number +>({ r = 17 } = { r: 18 }) => r : ({ r }?: { r: number; }) => number >r : number >17 : 17 >{ r: 18 } : { r: number; } @@ -210,8 +210,8 @@ (({ u = 22 } = { u: 23 }) => u)(); >(({ u = 22 } = { u: 23 }) => u)() : number ->(({ u = 22 } = { u: 23 }) => u) : ({u}?: { u?: number; }) => number ->({ u = 22 } = { u: 23 }) => u : ({u}?: { u?: number; }) => number +>(({ u = 22 } = { u: 23 }) => u) : ({ u }?: { u?: number; }) => number +>({ u = 22 } = { u: 23 }) => u : ({ u }?: { u?: number; }) => number >u : number >22 : 22 >{ u: 23 } : { u?: number; } diff --git a/tests/baselines/reference/controlFlowDestructuringParameters.types b/tests/baselines/reference/controlFlowDestructuringParameters.types index 7fdb1eded01..44755dca81b 100644 --- a/tests/baselines/reference/controlFlowDestructuringParameters.types +++ b/tests/baselines/reference/controlFlowDestructuringParameters.types @@ -12,7 +12,7 @@ >map : { (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U, U]; (this: [{ x: number; }, { x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U, U]; (this: [{ x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): [U, U]; (this: [{ x: number; }, { x: number; }], callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): [U, U]; (this: [{ x: number; }, { x: number; }], callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): [U, U]; (callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U): U[]; (callbackfn: (this: void, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: undefined): U[]; (callbackfn: (this: Z, value: { x: number; }, index: number, array: { x: number; }[]) => U, thisArg: Z): U[]; } ({ x }) => x ->({ x }) => x : (this: void, {x}: { x: number; }) => number +>({ x }) => x : (this: void, { x }: { x: number; }) => number >x : number >x : number diff --git a/tests/baselines/reference/declarationEmitBindingPatterns.types b/tests/baselines/reference/declarationEmitBindingPatterns.types index 1a47fbebf07..d49893dad94 100644 --- a/tests/baselines/reference/declarationEmitBindingPatterns.types +++ b/tests/baselines/reference/declarationEmitBindingPatterns.types @@ -1,7 +1,7 @@ === tests/cases/compiler/declarationEmitBindingPatterns.ts === const k = ({x: z = 'y'}) => { } ->k : ({x: z}: { x?: string; }) => void ->({x: z = 'y'}) => { } : ({x: z}: { x?: string; }) => void +>k : ({ x: z }: { x?: string; }) => void +>({x: z = 'y'}) => { } : ({ x: z }: { x?: string; }) => void >x : any >z : string >'y' : "y" @@ -10,7 +10,7 @@ var a; >a : any function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => void +>f : ({}?: any, []?: any, { p: {} }?: any) => void >a : any >a : any >p : any diff --git a/tests/baselines/reference/declarationEmitDestructuring1.types b/tests/baselines/reference/declarationEmitDestructuring1.types index abba67981d8..161ad94e54a 100644 --- a/tests/baselines/reference/declarationEmitDestructuring1.types +++ b/tests/baselines/reference/declarationEmitDestructuring1.types @@ -12,7 +12,7 @@ function far([a, [b], [[c]]]: [number, boolean[], string[][]]): void { } >c : string function bar({a1, b1, c1}: { a1: number, b1: boolean, c1: string }): void { } ->bar : ({a1, b1, c1}: { a1: number; b1: boolean; c1: string; }) => void +>bar : ({ a1, b1, c1 }: { a1: number; b1: boolean; c1: string; }) => void >a1 : number >b1 : boolean >c1 : string @@ -21,7 +21,7 @@ function bar({a1, b1, c1}: { a1: number, b1: boolean, c1: string }): void { } >c1 : string function baz({a2, b2: {b1, c1}}: { a2: number, b2: { b1: boolean, c1: string } }): void { } ->baz : ({a2, b2: {b1, c1}}: { a2: number; b2: { b1: boolean; c1: string; }; }) => void +>baz : ({ a2, b2: { b1, c1 } }: { a2: number; b2: { b1: boolean; c1: string; }; }) => void >a2 : number >b2 : any >b1 : boolean diff --git a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types index 0bf290bcf7d..fb8c57d019b 100644 --- a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types +++ b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.types @@ -11,7 +11,7 @@ function foo(...rest: any[]) { } function foo2( { x, y, z }?: { x: string; y: number; z: boolean }); ->foo2 : ({x, y, z}?: { x: string; y: number; z: boolean; }) => any +>foo2 : ({ x, y, z }?: { x: string; y: number; z: boolean; }) => any >x : string >y : number >z : boolean @@ -20,7 +20,7 @@ function foo2( { x, y, z }?: { x: string; y: number; z: boolean }); >z : boolean function foo2(...rest: any[]) { ->foo2 : ({x, y, z}?: { x: string; y: number; z: boolean; }) => any +>foo2 : ({ x, y, z }?: { x: string; y: number; z: boolean; }) => any >rest : any[] } diff --git a/tests/baselines/reference/destructureOptionalParameter.types b/tests/baselines/reference/destructureOptionalParameter.types index f007a992c9e..18a6d7675dd 100644 --- a/tests/baselines/reference/destructureOptionalParameter.types +++ b/tests/baselines/reference/destructureOptionalParameter.types @@ -1,13 +1,13 @@ === tests/cases/compiler/destructureOptionalParameter.ts === declare function f1({ a, b }?: { a: number, b: string }): void; ->f1 : ({a, b}?: { a: number; b: string; } | undefined) => void +>f1 : ({ a, b }?: { a: number; b: string; } | undefined) => void >a : number >b : string >a : number >b : string function f2({ a, b }: { a: number, b: number } = { a: 0, b: 0 }) { ->f2 : ({a, b}?: { a: number; b: number; }) => void +>f2 : ({ a, b }?: { a: number; b: number; }) => void >a : number >b : number >a : number diff --git a/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt b/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt index d76a4efe5f1..81c85f7c42b 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt +++ b/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt @@ -38,7 +38,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts( tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(47,13): error TS2463: A binding pattern parameter cannot be optional in an implementation signature. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(55,7): error TS2420: Class 'C4' incorrectly implements interface 'F2'. Types of property 'd4' are incompatible. - Type '({x, y, c}: { x: any; y: any; c: any; }) => void' is not assignable to type '({x, y, z}?: { x: any; y: any; z: any; }) => any'. + Type '({ x, y, c }: { x: any; y: any; c: any; }) => void' is not assignable to type '({ x, y, z }?: { x: any; y: any; z: any; }) => any'. Types of parameters '__0' and '__0' are incompatible. Type '{ x: any; y: any; z: any; }' is not assignable to type '{ x: any; y: any; c: any; }'. Property 'c' is missing in type '{ x: any; y: any; z: any; }'. @@ -162,7 +162,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts( ~~ !!! error TS2420: Class 'C4' incorrectly implements interface 'F2'. !!! error TS2420: Types of property 'd4' are incompatible. -!!! error TS2420: Type '({x, y, c}: { x: any; y: any; c: any; }) => void' is not assignable to type '({x, y, z}?: { x: any; y: any; z: any; }) => any'. +!!! error TS2420: Type '({ x, y, c }: { x: any; y: any; c: any; }) => void' is not assignable to type '({ x, y, z }?: { x: any; y: any; z: any; }) => any'. !!! error TS2420: Types of parameters '__0' and '__0' are incompatible. !!! error TS2420: Type '{ x: any; y: any; z: any; }' is not assignable to type '{ x: any; y: any; c: any; }'. !!! error TS2420: Property 'c' is missing in type '{ x: any; y: any; z: any; }'. diff --git a/tests/baselines/reference/destructuringParameterDeclaration7ES5.types b/tests/baselines/reference/destructuringParameterDeclaration7ES5.types index 502a176596a..40a07f02276 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration7ES5.types +++ b/tests/baselines/reference/destructuringParameterDeclaration7ES5.types @@ -10,13 +10,13 @@ interface ISomething { } function foo({}, {foo, bar}: ISomething) {} ->foo : ({}: {}, {foo, bar}: ISomething) => void +>foo : ({}: {}, { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething function baz([], {foo, bar}: ISomething) {} ->baz : ([]: any[], {foo, bar}: ISomething) => void +>baz : ([]: any[], { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething diff --git a/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types b/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types index 542407cabe2..607c34cdd37 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types +++ b/tests/baselines/reference/destructuringParameterDeclaration7ES5iterable.types @@ -10,13 +10,13 @@ interface ISomething { } function foo({}, {foo, bar}: ISomething) {} ->foo : ({}: {}, {foo, bar}: ISomething) => void +>foo : ({}: {}, { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething function baz([], {foo, bar}: ISomething) {} ->baz : ([]: any[], {foo, bar}: ISomething) => void +>baz : ([]: any[], { foo, bar }: ISomething) => void >foo : string >bar : string >ISomething : ISomething diff --git a/tests/baselines/reference/destructuringWithGenericParameter.types b/tests/baselines/reference/destructuringWithGenericParameter.types index 07a86e679a9..430d6e0faca 100644 --- a/tests/baselines/reference/destructuringWithGenericParameter.types +++ b/tests/baselines/reference/destructuringWithGenericParameter.types @@ -36,7 +36,7 @@ genericFunction(genericObject, ({greeting}) => { >genericFunction(genericObject, ({greeting}) => { var s = greeting.toLocaleLowerCase(); // Greeting should be of type string}) : void >genericFunction : (object: GenericClass, callback: (payload: T) => void) => void >genericObject : GenericClass<{ greeting: string; }> ->({greeting}) => { var s = greeting.toLocaleLowerCase(); // Greeting should be of type string} : ({greeting}: { greeting: string; }) => void +>({greeting}) => { var s = greeting.toLocaleLowerCase(); // Greeting should be of type string} : ({ greeting }: { greeting: string; }) => void >greeting : string var s = greeting.toLocaleLowerCase(); // Greeting should be of type string diff --git a/tests/baselines/reference/destructuringWithLiteralInitializers.types b/tests/baselines/reference/destructuringWithLiteralInitializers.types index 43391515014..51c432f7605 100644 --- a/tests/baselines/reference/destructuringWithLiteralInitializers.types +++ b/tests/baselines/reference/destructuringWithLiteralInitializers.types @@ -1,13 +1,13 @@ === tests/cases/conformance/es6/destructuring/destructuringWithLiteralInitializers.ts === // (arg: { x: any, y: any }) => void function f1({ x, y }) { } ->f1 : ({x, y}: { x: any; y: any; }) => void +>f1 : ({ x, y }: { x: any; y: any; }) => void >x : any >y : any f1({ x: 1, y: 1 }); >f1({ x: 1, y: 1 }) : void ->f1 : ({x, y}: { x: any; y: any; }) => void +>f1 : ({ x, y }: { x: any; y: any; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -16,21 +16,21 @@ f1({ x: 1, y: 1 }); // (arg: { x: any, y?: number }) => void function f2({ x, y = 0 }) { } ->f2 : ({x, y}: { x: any; y?: number; }) => void +>f2 : ({ x, y }: { x: any; y?: number; }) => void >x : any >y : number >0 : 0 f2({ x: 1 }); >f2({ x: 1 }) : void ->f2 : ({x, y}: { x: any; y?: number; }) => void +>f2 : ({ x, y }: { x: any; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f2({ x: 1, y: 1 }); >f2({ x: 1, y: 1 }) : void ->f2 : ({x, y}: { x: any; y?: number; }) => void +>f2 : ({ x, y }: { x: any; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -39,7 +39,7 @@ f2({ x: 1, y: 1 }); // (arg: { x?: number, y?: number }) => void function f3({ x = 0, y = 0 }) { } ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >x : number >0 : 0 >y : number @@ -47,26 +47,26 @@ function f3({ x = 0, y = 0 }) { } f3({}); >f3({}) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{} : {} f3({ x: 1 }); >f3({ x: 1 }) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f3({ y: 1 }); >f3({ y: 1 }) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{ y: 1 } : { y: number; } >y : number >1 : 1 f3({ x: 1, y: 1 }); >f3({ x: 1, y: 1 }) : void ->f3 : ({x, y}: { x?: number; y?: number; }) => void +>f3 : ({ x, y }: { x?: number; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -75,7 +75,7 @@ f3({ x: 1, y: 1 }); // (arg?: { x: number, y: number }) => void function f4({ x, y } = { x: 0, y: 0 }) { } ->f4 : ({x, y}?: { x: number; y: number; }) => void +>f4 : ({ x, y }?: { x: number; y: number; }) => void >x : number >y : number >{ x: 0, y: 0 } : { x: number; y: number; } @@ -86,11 +86,11 @@ function f4({ x, y } = { x: 0, y: 0 }) { } f4(); >f4() : void ->f4 : ({x, y}?: { x: number; y: number; }) => void +>f4 : ({ x, y }?: { x: number; y: number; }) => void f4({ x: 1, y: 1 }); >f4({ x: 1, y: 1 }) : void ->f4 : ({x, y}?: { x: number; y: number; }) => void +>f4 : ({ x, y }?: { x: number; y: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -99,7 +99,7 @@ f4({ x: 1, y: 1 }); // (arg?: { x: number, y?: number }) => void function f5({ x, y = 0 } = { x: 0 }) { } ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void >x : number >y : number >0 : 0 @@ -109,18 +109,18 @@ function f5({ x, y = 0 } = { x: 0 }) { } f5(); >f5() : void ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void f5({ x: 1 }); >f5({ x: 1 }) : void ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f5({ x: 1, y: 1 }); >f5({ x: 1, y: 1 }) : void ->f5 : ({x, y}?: { x: number; y?: number; }) => void +>f5 : ({ x, y }?: { x: number; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -129,7 +129,7 @@ f5({ x: 1, y: 1 }); // (arg?: { x?: number, y?: number }) => void function f6({ x = 0, y = 0 } = {}) { } ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >x : number >0 : 0 >y : number @@ -138,30 +138,30 @@ function f6({ x = 0, y = 0 } = {}) { } f6(); >f6() : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void f6({}); >f6({}) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{} : {} f6({ x: 1 }); >f6({ x: 1 }) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{ x: 1 } : { x: number; } >x : number >1 : 1 f6({ y: 1 }); >f6({ y: 1 }) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{ y: 1 } : { y: number; } >y : number >1 : 1 f6({ x: 1, y: 1 }); >f6({ x: 1, y: 1 }) : void ->f6 : ({x, y}?: { x?: number; y?: number; }) => void +>f6 : ({ x, y }?: { x?: number; y?: number; }) => void >{ x: 1, y: 1 } : { x: number; y: number; } >x : number >1 : 1 @@ -170,7 +170,7 @@ f6({ x: 1, y: 1 }); // (arg?: { a: { x?: number, y?: number } }) => void function f7({ a: { x = 0, y = 0 } } = { a: {} }) { } ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >a : any >x : number >0 : 0 @@ -182,18 +182,18 @@ function f7({ a: { x = 0, y = 0 } } = { a: {} }) { } f7(); >f7() : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void f7({ a: {} }); >f7({ a: {} }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: {} } : { a: {}; } >a : {} >{} : {} f7({ a: { x: 1 } }); >f7({ a: { x: 1 } }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: { x: 1 } } : { a: { x: number; }; } >a : { x: number; } >{ x: 1 } : { x: number; } @@ -202,7 +202,7 @@ f7({ a: { x: 1 } }); f7({ a: { y: 1 } }); >f7({ a: { y: 1 } }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: { y: 1 } } : { a: { y: number; }; } >a : { y: number; } >{ y: 1 } : { y: number; } @@ -211,7 +211,7 @@ f7({ a: { y: 1 } }); f7({ a: { x: 1, y: 1 } }); >f7({ a: { x: 1, y: 1 } }) : void ->f7 : ({a: {x, y}}?: { a: { x?: number; y?: number; }; }) => void +>f7 : ({ a: { x, y } }?: { a: { x?: number; y?: number; }; }) => void >{ a: { x: 1, y: 1 } } : { a: { x: number; y: number; }; } >a : { x: number; y: number; } >{ x: 1, y: 1 } : { x: number; y: number; } diff --git a/tests/baselines/reference/emitArrowFunctionES6.types b/tests/baselines/reference/emitArrowFunctionES6.types index c434e4b285a..314d5e464b7 100644 --- a/tests/baselines/reference/emitArrowFunctionES6.types +++ b/tests/baselines/reference/emitArrowFunctionES6.types @@ -70,25 +70,25 @@ var p5 = ([a = 1]) => { }; >1 : 1 var p6 = ({ a }) => { }; ->p6 : ({a}: { a: any; }) => void ->({ a }) => { } : ({a}: { a: any; }) => void +>p6 : ({ a }: { a: any; }) => void +>({ a }) => { } : ({ a }: { a: any; }) => void >a : any var p7 = ({ a: { b } }) => { }; ->p7 : ({a: {b}}: { a: { b: any; }; }) => void ->({ a: { b } }) => { } : ({a: {b}}: { a: { b: any; }; }) => void +>p7 : ({ a: { b } }: { a: { b: any; }; }) => void +>({ a: { b } }) => { } : ({ a: { b } }: { a: { b: any; }; }) => void >a : any >b : any var p8 = ({ a = 1 }) => { }; ->p8 : ({a}: { a?: number; }) => void ->({ a = 1 }) => { } : ({a}: { a?: number; }) => void +>p8 : ({ a }: { a?: number; }) => void +>({ a = 1 }) => { } : ({ a }: { a?: number; }) => void >a : number >1 : 1 var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; ->p9 : ({a: {b}}: { a?: { b?: number; }; }) => void ->({ a: { b = 1 } = { b: 1 } }) => { } : ({a: {b}}: { a?: { b?: number; }; }) => void +>p9 : ({ a: { b } }: { a?: { b?: number; }; }) => void +>({ a: { b = 1 } = { b: 1 } }) => { } : ({ a: { b } }: { a?: { b?: number; }; }) => void >a : any >b : number >1 : 1 @@ -97,8 +97,8 @@ var p9 = ({ a: { b = 1 } = { b: 1 } }) => { }; >1 : 1 var p10 = ([{ value, done }]) => { }; ->p10 : ([{value, done}]: [{ value: any; done: any; }]) => void ->([{ value, done }]) => { } : ([{value, done}]: [{ value: any; done: any; }]) => void +>p10 : ([{ value, done }]: [{ value: any; done: any; }]) => void +>([{ value, done }]) => { } : ([{ value, done }]: [{ value: any; done: any; }]) => void >value : any >done : any diff --git a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types index c61c80c5b3d..7db78f29829 100644 --- a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types +++ b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5.types @@ -61,7 +61,7 @@ } function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => ({}?: any, []?: any, {p: {}}?: any) => any +>f : ({}?: any, []?: any, { p: {} }?: any) => ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any @@ -69,7 +69,7 @@ >a : any return ({} = a, [] = a, { p: {} = a } = a) => a; ->({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, {p: {}}?: any) => any +>({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any diff --git a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types index 9c623fd8879..d5559047aba 100644 --- a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types +++ b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.types @@ -61,7 +61,7 @@ } function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => ({}?: any, []?: any, {p: {}}?: any) => any +>f : ({}?: any, []?: any, { p: {} }?: any) => ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any @@ -69,7 +69,7 @@ >a : any return ({} = a, [] = a, { p: {} = a } = a) => a; ->({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, {p: {}}?: any) => any +>({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any diff --git a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types index 48d5f40b971..535562296a3 100644 --- a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types +++ b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES6.types @@ -61,7 +61,7 @@ } function f({} = a, [] = a, { p: {} = a} = a) { ->f : ({}?: any, []?: any, {p: {}}?: any) => ({}?: any, []?: any, {p: {}}?: any) => any +>f : ({}?: any, []?: any, { p: {} }?: any) => ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any @@ -69,7 +69,7 @@ >a : any return ({} = a, [] = a, { p: {} = a } = a) => a; ->({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, {p: {}}?: any) => any +>({} = a, [] = a, { p: {} = a } = a) => a : ({}?: any, []?: any, { p: {} }?: any) => any >a : any >a : any >p : any diff --git a/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types b/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types index 7b1a2d8e6ff..161870de77c 100644 --- a/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types +++ b/tests/baselines/reference/fallbackToBindingPatternForTypeInference.types @@ -9,7 +9,7 @@ declare function trans(f: (x: T) => string): number; trans(({a}) => a); >trans(({a}) => a) : number >trans : (f: (x: T) => string) => number ->({a}) => a : ({a}: { a: any; }) => any +>({a}) => a : ({ a }: { a: any; }) => any >a : any >a : any @@ -24,7 +24,7 @@ trans(([b,c]) => 'foo'); trans(({d: [e,f]}) => 'foo'); >trans(({d: [e,f]}) => 'foo') : number >trans : (f: (x: T) => string) => number ->({d: [e,f]}) => 'foo' : ({d: [e, f]}: { d: [any, any]; }) => string +>({d: [e,f]}) => 'foo' : ({ d: [e, f] }: { d: [any, any]; }) => string >d : any >e : any >f : any @@ -33,7 +33,7 @@ trans(({d: [e,f]}) => 'foo'); trans(([{g},{h}]) => 'foo'); >trans(([{g},{h}]) => 'foo') : number >trans : (f: (x: T) => string) => number ->([{g},{h}]) => 'foo' : ([{g}, {h}]: [{ g: any; }, { h: any; }]) => string +>([{g},{h}]) => 'foo' : ([{ g }, { h }]: [{ g: any; }, { h: any; }]) => string >g : any >h : any >'foo' : "foo" @@ -41,7 +41,7 @@ trans(([{g},{h}]) => 'foo'); trans(({a, b = 10}) => a); >trans(({a, b = 10}) => a) : number >trans : (f: (x: T) => string) => number ->({a, b = 10}) => a : ({a, b}: { a: any; b?: number; }) => any +>({a, b = 10}) => a : ({ a, b }: { a: any; b?: number; }) => any >a : any >b : number >10 : 10 diff --git a/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types b/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types index a399e59e3c3..eb16207afed 100644 --- a/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types +++ b/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.types @@ -10,7 +10,7 @@ export class Bar { >Bar : Bar private bar({ a, }: Arg): number { ->bar : ({a}: { a: number; }) => number +>bar : ({ a, }: { a: number; }) => number >a : number >Arg : { a: number; } @@ -22,6 +22,6 @@ export declare class Bar2 { >Bar2 : Bar2 private bar({ a, }); ->bar : ({a}: { a: any; }) => any +>bar : ({ a, }: { a: any; }) => any >a : any } diff --git a/tests/baselines/reference/objectRest.types b/tests/baselines/reference/objectRest.types index 2fff9a3c729..dff8830e818 100644 --- a/tests/baselines/reference/objectRest.types +++ b/tests/baselines/reference/objectRest.types @@ -218,8 +218,8 @@ var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; >o : { a: number; b: string; } var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; ->noContextualType : ({aNumber, ...notEmptyObject}: { [x: string]: any; aNumber?: number; }) => any ->({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes : ({aNumber, ...notEmptyObject}: { [x: string]: any; aNumber?: number; }) => any +>noContextualType : ({ aNumber, ...notEmptyObject }: { [x: string]: any; aNumber?: number; }) => any +>({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes : ({ aNumber, ...notEmptyObject }: { [x: string]: any; aNumber?: number; }) => any >aNumber : number >12 : 12 >notEmptyObject : { [x: string]: any; } diff --git a/tests/baselines/reference/objectRestParameter.types b/tests/baselines/reference/objectRestParameter.types index e56e7cebfc7..3d0d1bb619b 100644 --- a/tests/baselines/reference/objectRestParameter.types +++ b/tests/baselines/reference/objectRestParameter.types @@ -1,6 +1,6 @@ === tests/cases/conformance/types/rest/objectRestParameter.ts === function cloneAgain({ a, ...clone }: { a: number, b: string }): void { ->cloneAgain : ({a, ...clone}: { a: number; b: string; }) => void +>cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -19,7 +19,7 @@ declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); suddenly(({ x: a, ...rest }) => rest.y); >suddenly(({ x: a, ...rest }) => rest.y) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: a, ...rest }) => rest.y : ({x: a, ...rest}: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } >rest : { y: string; } @@ -30,7 +30,7 @@ suddenly(({ x: a, ...rest }) => rest.y); suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({x: {z, ...nested}, ...rest}?: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({ x: { z, ...nested }, ...rest }?: { x: { z: any; ka: any; }; y: string; }) => string >x : any >z : any >12 : 12 @@ -57,7 +57,7 @@ class C { >C : C m({ a, ...clone }: { a: number, b: string}): void { ->m : ({a, ...clone}: { a: number; b: string; }) => void +>m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -76,7 +76,7 @@ class C { } } function foobar({ bar={}, ...opts }: any = {}) { ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >bar : {} >{} : {} >opts : any @@ -84,18 +84,18 @@ function foobar({ bar={}, ...opts }: any = {}) { } foobar(); >foobar() : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void foobar({ baz: 'hello' }); >foobar({ baz: 'hello' }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ baz: 'hello' } : { baz: string; } >baz : string >'hello' : "hello" foobar({ bar: { greeting: 'hello' } }); >foobar({ bar: { greeting: 'hello' } }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ bar: { greeting: 'hello' } } : { bar: { greeting: string; }; } >bar : { greeting: string; } >{ greeting: 'hello' } : { greeting: string; } diff --git a/tests/baselines/reference/objectRestParameterES5.types b/tests/baselines/reference/objectRestParameterES5.types index 009d810782b..e0ebee39317 100644 --- a/tests/baselines/reference/objectRestParameterES5.types +++ b/tests/baselines/reference/objectRestParameterES5.types @@ -1,6 +1,6 @@ === tests/cases/conformance/types/rest/objectRestParameterES5.ts === function cloneAgain({ a, ...clone }: { a: number, b: string }): void { ->cloneAgain : ({a, ...clone}: { a: number; b: string; }) => void +>cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -19,7 +19,7 @@ declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); suddenly(({ x: a, ...rest }) => rest.y); >suddenly(({ x: a, ...rest }) => rest.y) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: a, ...rest }) => rest.y : ({x: a, ...rest}: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } >rest : { y: string; } @@ -30,7 +30,7 @@ suddenly(({ x: a, ...rest }) => rest.y); suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka) : any >suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any ->({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({x: {z, ...nested}, ...rest}?: { x: { z: any; ka: any; }; y: string; }) => string +>({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({ x: { z, ...nested }, ...rest }?: { x: { z: any; ka: any; }; y: string; }) => string >x : any >z : any >12 : 12 @@ -57,7 +57,7 @@ class C { >C : C m({ a, ...clone }: { a: number, b: string}): void { ->m : ({a, ...clone}: { a: number; b: string; }) => void +>m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number >clone : { b: string; } >a : number @@ -76,7 +76,7 @@ class C { } } function foobar({ bar={}, ...opts }: any = {}) { ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >bar : {} >{} : {} >opts : any @@ -84,18 +84,18 @@ function foobar({ bar={}, ...opts }: any = {}) { } foobar(); >foobar() : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void foobar({ baz: 'hello' }); >foobar({ baz: 'hello' }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ baz: 'hello' } : { baz: string; } >baz : string >'hello' : "hello" foobar({ bar: { greeting: 'hello' } }); >foobar({ bar: { greeting: 'hello' } }) : void ->foobar : ({bar, ...opts}?: any) => void +>foobar : ({ bar, ...opts }?: any) => void >{ bar: { greeting: 'hello' } } : { bar: { greeting: string; }; } >bar : { greeting: string; } >{ greeting: 'hello' } : { greeting: string; } diff --git a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types index 46b5983a514..d276812c01d 100644 --- a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types +++ b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types @@ -10,7 +10,7 @@ interface Foo { } function foobar({ bar = {}, ...opts }: Foo = {}) { ->foobar : ({bar, ...opts}?: Foo) => void +>foobar : ({ bar, ...opts }?: Foo) => void >bar : any >{} : {} >opts : { baz?: any; } diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types index eef87d57c45..bbd13dddf57 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPattern.types @@ -37,7 +37,7 @@ var robotA: Robot = { name: "mower", skills: { primary: "mowing", secondary: "no >"none" : "none" function foo1({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) { ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) => void >skills : any >primary : any >primaryA : string @@ -53,7 +53,7 @@ function foo1({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) { >primaryA : string } function foo2({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) { ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) => void >name : any >nameC : string >skills : any @@ -71,7 +71,7 @@ function foo2({ name: nameC, skills: { primary: primaryB, secondary: secondaryB >secondaryB : string } function foo3({ skills }: Robot) { ->foo3 : ({skills}: Robot) => void +>foo3 : ({ skills }: Robot) => void >skills : { primary: string; secondary: string; } >Robot : Robot @@ -87,12 +87,12 @@ function foo3({ skills }: Robot) { foo1(robotA); >foo1(robotA) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) => void >robotA : Robot foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -105,12 +105,12 @@ foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) => void >robotA : Robot foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -123,12 +123,12 @@ foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo3(robotA); >foo3(robotA) : void ->foo3 : ({skills}: Robot) => void +>foo3 : ({ skills }: Robot) => void >robotA : Robot foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo3 : ({skills}: Robot) => void +>foo3 : ({ skills }: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types index 9f5b16407ca..d9c8b319752 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterNestedObjectBindingPatternDefaultValues.types @@ -37,7 +37,7 @@ var robotA: Robot = { name: "mower", skills: { primary: "mowing", secondary: "no >"none" : "none" function foo1( ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}?: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }?: Robot) => void { skills: { >skills : any @@ -71,7 +71,7 @@ function foo1( >primaryA : string } function foo2( ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}?: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }?: Robot) => void { name: nameC = "name", >name : any @@ -110,7 +110,7 @@ function foo2( >secondaryB : string } function foo3({ skills = { primary: "SomeSkill", secondary: "someSkill" } }: Robot = robotA) { ->foo3 : ({skills}?: Robot) => void +>foo3 : ({ skills }?: Robot) => void >skills : { primary?: string; secondary?: string; } >{ primary: "SomeSkill", secondary: "someSkill" } : { primary: string; secondary: string; } >primary : string @@ -132,12 +132,12 @@ function foo3({ skills = { primary: "SomeSkill", secondary: "someSkill" } }: Ro foo1(robotA); >foo1(robotA) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}?: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }?: Robot) => void >robotA : Robot foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo1 : ({skills: {primary: primaryA, secondary: secondaryA}}?: Robot) => void +>foo1 : ({ skills: { primary: primaryA, secondary: secondaryA } }?: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -150,12 +150,12 @@ foo1({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}?: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }?: Robot) => void >robotA : Robot foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo2 : ({name: nameC, skills: {primary: primaryB, secondary: secondaryB}}?: Robot) => void +>foo2 : ({ name: nameC, skills: { primary: primaryB, secondary: secondaryB } }?: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" @@ -168,12 +168,12 @@ foo2({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" foo3(robotA); >foo3(robotA) : void ->foo3 : ({skills}?: Robot) => void +>foo3 : ({ skills }?: Robot) => void >robotA : Robot foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }); >foo3({ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } }) : void ->foo3 : ({skills}?: Robot) => void +>foo3 : ({ skills }?: Robot) => void >{ name: "Edger", skills: { primary: "edging", secondary: "branch trimming" } } : { name: string; skills: { primary: string; secondary: string; }; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types index 225071a3d2e..5185ab35994 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPattern.types @@ -29,7 +29,7 @@ var robotA: Robot = { name: "mower", skill: "mowing" }; >"mowing" : "mowing" function foo1({ name: nameA }: Robot) { ->foo1 : ({name: nameA}: Robot) => void +>foo1 : ({ name: nameA }: Robot) => void >name : any >nameA : string >Robot : Robot @@ -42,7 +42,7 @@ function foo1({ name: nameA }: Robot) { >nameA : string } function foo2({ name: nameB, skill: skillB }: Robot) { ->foo2 : ({name: nameB, skill: skillB}: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }: Robot) => void >name : any >nameB : string >skill : any @@ -57,7 +57,7 @@ function foo2({ name: nameB, skill: skillB }: Robot) { >nameB : string } function foo3({ name }: Robot) { ->foo3 : ({name}: Robot) => void +>foo3 : ({ name }: Robot) => void >name : string >Robot : Robot @@ -71,12 +71,12 @@ function foo3({ name }: Robot) { foo1(robotA); >foo1(robotA) : void ->foo1 : ({name: nameA}: Robot) => void +>foo1 : ({ name: nameA }: Robot) => void >robotA : Robot foo1({ name: "Edger", skill: "cutting edges" }); >foo1({ name: "Edger", skill: "cutting edges" }) : void ->foo1 : ({name: nameA}: Robot) => void +>foo1 : ({ name: nameA }: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -85,12 +85,12 @@ foo1({ name: "Edger", skill: "cutting edges" }); foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameB, skill: skillB}: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }: Robot) => void >robotA : Robot foo2({ name: "Edger", skill: "cutting edges" }); >foo2({ name: "Edger", skill: "cutting edges" }) : void ->foo2 : ({name: nameB, skill: skillB}: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -99,12 +99,12 @@ foo2({ name: "Edger", skill: "cutting edges" }); foo3(robotA); >foo3(robotA) : void ->foo3 : ({name}: Robot) => void +>foo3 : ({ name }: Robot) => void >robotA : Robot foo3({ name: "Edger", skill: "cutting edges" }); >foo3({ name: "Edger", skill: "cutting edges" }) : void ->foo3 : ({name}: Robot) => void +>foo3 : ({ name }: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types index db6a8bcab29..ca6670e5561 100644 --- a/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types +++ b/tests/baselines/reference/sourceMapValidationDestructuringParameterObjectBindingPatternDefaultValues.types @@ -29,7 +29,7 @@ var robotA: Robot = { name: "mower", skill: "mowing" }; >"mowing" : "mowing" function foo1({ name: nameA = "" }: Robot = { }) { ->foo1 : ({name: nameA}?: Robot) => void +>foo1 : ({ name: nameA }?: Robot) => void >name : any >nameA : string >"" : "" @@ -44,7 +44,7 @@ function foo1({ name: nameA = "" }: Robot = { }) { >nameA : string } function foo2({ name: nameB = "", skill: skillB = "noSkill" }: Robot = {}) { ->foo2 : ({name: nameB, skill: skillB}?: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }?: Robot) => void >name : any >nameB : string >"" : "" @@ -62,7 +62,7 @@ function foo2({ name: nameB = "", skill: skillB = "noSkill" }: Robot = { >nameB : string } function foo3({ name = "" }: Robot = {}) { ->foo3 : ({name}?: Robot) => void +>foo3 : ({ name }?: Robot) => void >name : string >"" : "" >Robot : Robot @@ -78,12 +78,12 @@ function foo3({ name = "" }: Robot = {}) { foo1(robotA); >foo1(robotA) : void ->foo1 : ({name: nameA}?: Robot) => void +>foo1 : ({ name: nameA }?: Robot) => void >robotA : Robot foo1({ name: "Edger", skill: "cutting edges" }); >foo1({ name: "Edger", skill: "cutting edges" }) : void ->foo1 : ({name: nameA}?: Robot) => void +>foo1 : ({ name: nameA }?: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -92,12 +92,12 @@ foo1({ name: "Edger", skill: "cutting edges" }); foo2(robotA); >foo2(robotA) : void ->foo2 : ({name: nameB, skill: skillB}?: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }?: Robot) => void >robotA : Robot foo2({ name: "Edger", skill: "cutting edges" }); >foo2({ name: "Edger", skill: "cutting edges" }) : void ->foo2 : ({name: nameB, skill: skillB}?: Robot) => void +>foo2 : ({ name: nameB, skill: skillB }?: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" @@ -106,12 +106,12 @@ foo2({ name: "Edger", skill: "cutting edges" }); foo3(robotA); >foo3(robotA) : void ->foo3 : ({name}?: Robot) => void +>foo3 : ({ name }?: Robot) => void >robotA : Robot foo3({ name: "Edger", skill: "cutting edges" }); >foo3({ name: "Edger", skill: "cutting edges" }) : void ->foo3 : ({name}?: Robot) => void +>foo3 : ({ name }?: Robot) => void >{ name: "Edger", skill: "cutting edges" } : { name: string; skill: string; } >name : string >"Edger" : "Edger" diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution13.types b/tests/baselines/reference/tsxSpreadAttributesResolution13.types index 5b5ada68613..0ad324c25b1 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution13.types +++ b/tests/baselines/reference/tsxSpreadAttributesResolution13.types @@ -28,7 +28,7 @@ export default function Component(props: ComponentProps) { > : JSX.Element ->ChildComponent : ({property1}: AnotherComponentProps) => JSX.Element +>ChildComponent : ({ property1 }: AnotherComponentProps) => JSX.Element >props : ComponentProps ); @@ -37,7 +37,7 @@ export default function Component(props: ComponentProps) { return (); >() : JSX.Element > : JSX.Element ->ChildComponent : ({property1}: AnotherComponentProps) => JSX.Element +>ChildComponent : ({ property1 }: AnotherComponentProps) => JSX.Element >props : ComponentProps >property1 : string } @@ -51,7 +51,7 @@ interface AnotherComponentProps { } function ChildComponent({ property1 }: AnotherComponentProps) { ->ChildComponent : ({property1}: AnotherComponentProps) => JSX.Element +>ChildComponent : ({ property1 }: AnotherComponentProps) => JSX.Element >property1 : string >AnotherComponentProps : AnotherComponentProps diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution15.types b/tests/baselines/reference/tsxSpreadAttributesResolution15.types index dbcb6541a03..152ad3f696e 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution15.types +++ b/tests/baselines/reference/tsxSpreadAttributesResolution15.types @@ -22,7 +22,7 @@ export default function Component(props: ComponentProps) { > : JSX.Element ->AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element +>AnotherComponent : ({ property1 }: AnotherComponentProps) => JSX.Element >props : ComponentProps >property2 : true >AnotherProperty1 : string @@ -44,7 +44,7 @@ interface AnotherComponentProps { } function AnotherComponent({ property1 }: AnotherComponentProps) { ->AnotherComponent : ({property1}: AnotherComponentProps) => JSX.Element +>AnotherComponent : ({ property1 }: AnotherComponentProps) => JSX.Element >property1 : string >AnotherComponentProps : AnotherComponentProps diff --git a/tests/baselines/reference/tsxSpreadChildren.types b/tests/baselines/reference/tsxSpreadChildren.types index 7f4609c30b8..c762e45b593 100644 --- a/tests/baselines/reference/tsxSpreadChildren.types +++ b/tests/baselines/reference/tsxSpreadChildren.types @@ -53,7 +53,7 @@ function Todo(prop: { key: number, todo: string }) { >div : any } function TodoList({ todos }: TodoListProps) { ->TodoList : ({todos}: TodoListProps) => JSX.Element +>TodoList : ({ todos }: TodoListProps) => JSX.Element >todos : TodoProp[] >TodoListProps : TodoListProps @@ -88,6 +88,6 @@ let x: TodoListProps; > : JSX.Element ->TodoList : ({todos}: TodoListProps) => JSX.Element +>TodoList : ({ todos }: TodoListProps) => JSX.Element >x : TodoListProps diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types b/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types index 8e288ebd34a..875f8018a95 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload1.types @@ -79,21 +79,21 @@ const c5 = Hello declare function TestingOneThing({y1: string}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >y1 : any >string : any >JSX : any >Element : JSX.Element declare function TestingOneThing(j: {"extra-data": string, yy?: string}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >j : { "extra-data": string; yy?: string; } >yy : string >JSX : any >Element : JSX.Element declare function TestingOneThing(n: {yy: number, direction?: number}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >n : { yy: number; direction?: number; } >yy : number >direction : number @@ -101,7 +101,7 @@ declare function TestingOneThing(n: {yy: number, direction?: number}): JSX.Eleme >Element : JSX.Element declare function TestingOneThing(n: {yy: string, name: string}): JSX.Element; ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >n : { yy: string; name: string; } >yy : string >name : string @@ -112,27 +112,27 @@ declare function TestingOneThing(n: {yy: string, name: string}): JSX.Element; const d1 = ; >d1 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >y1 : true >extra-data : true const d2 = ; >d2 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string const d3 = ; >d3 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string >yy : string const d4 = ; >d4 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string >yy : number >9 : 9 @@ -142,7 +142,7 @@ const d4 = ; const d5 = ; >d5 : JSX.Element > : JSX.Element ->TestingOneThing : { ({y1: string}: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } +>TestingOneThing : { ({ y1: string }: { y1: any; }): JSX.Element; (j: { "extra-data": string; yy?: string; }): JSX.Element; (n: { yy: number; direction?: number; }): JSX.Element; (n: { yy: string; name: string; }): JSX.Element; } >extra-data : string >yy : string >name : string diff --git a/tests/baselines/reference/tsxStatelessFunctionComponents3.types b/tests/baselines/reference/tsxStatelessFunctionComponents3.types index 879f8c75cdf..e01c8454aa7 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponents3.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponents3.types @@ -40,7 +40,7 @@ var App: React.StatelessComponent<{ children }> = ({children}) => ( >React : any >StatelessComponent : React.StatelessComponent

>children : any ->({children}) => (

) : ({children}: { children: any; } & { children?: React.ReactNode; }) => JSX.Element +>({children}) => (
) : ({ children }: { children: any; } & { children?: React.ReactNode; }) => JSX.Element >children : any >(
) : JSX.Element From b40bc0c01954a4467a44fd406ce77300ffa45fdf Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Tue, 23 May 2017 14:31:37 -0700 Subject: [PATCH 277/282] Add type alias for TypeReferenceType and convert to use JSDoc --- src/compiler/checker.ts | 30 ++++++++++++++++++------------ src/compiler/types.ts | 2 ++ 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 07c20ad7aa0..7b084a0f261 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6696,8 +6696,10 @@ namespace ts { return length(type.target.typeParameters); } - // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol, typeArgs: Type[]): Type { + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node: TypeReferenceType, symbol: Symbol, typeArgs: Type[]): Type { const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); const typeParameters = type.localTypeParameters; if (typeParameters) { @@ -6738,10 +6740,12 @@ namespace ts { return instantiation; } - // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include - // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the - // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol, typeArguments: Type[]): Type { + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ + function getTypeFromTypeAliasReference(node: TypeReferenceType, symbol: Symbol, typeArguments: Type[]): Type { const type = getDeclaredTypeOfSymbol(symbol); const typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { @@ -6766,8 +6770,10 @@ namespace ts { return type; } - // Get type from reference to named type that cannot be generic (enum or type parameter) - function getTypeFromNonGenericTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { + /** + * Get type from reference to named type that cannot be generic (enum or type parameter) + */ + function getTypeFromNonGenericTypeReference(node: TypeReferenceType, symbol: Symbol): Type { if (node.typeArguments) { error(node, Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); return unknownType; @@ -6775,7 +6781,7 @@ namespace ts { return getDeclaredTypeOfSymbol(symbol); } - function getTypeReferenceName(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): EntityNameOrEntityNameExpression | undefined { + function getTypeReferenceName(node: TypeReferenceType): EntityNameOrEntityNameExpression | undefined { switch (node.kind) { case SyntaxKind.TypeReference: return (node).typeName; @@ -6803,7 +6809,7 @@ namespace ts { return resolveEntityName(typeReferenceName, SymbolFlags.Type) || unknownSymbol; } - function getTypeReferenceType(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol) { + function getTypeReferenceType(node: TypeReferenceType, symbol: Symbol) { const typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { @@ -6862,7 +6868,7 @@ namespace ts { return strictNullChecks ? getUnionType([type, nullType]) : type; } - function getTypeFromTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): Type { + function getTypeFromTypeReference(node: TypeReferenceType): Type { const links = getNodeLinks(node); if (!links.resolvedType) { let symbol: Symbol; @@ -6893,7 +6899,7 @@ namespace ts { return links.resolvedType; } - function typeArgumentsFromTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): Type[] { + function typeArgumentsFromTypeReferenceNode(node: TypeReferenceType): Type[] { return map(node.typeArguments, getTypeFromTypeNode); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a8da09a11c5..73a2e46be90 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -892,6 +892,8 @@ namespace ts { kind: SyntaxKind.ConstructorType; } + export type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference; + export interface TypeReferenceNode extends TypeNode { kind: SyntaxKind.TypeReference; typeName: EntityName; From 3d9a1babf78cc5115fe6b1c4295dd9c3de95ef5f Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Tue, 23 May 2017 16:10:56 -0700 Subject: [PATCH 278/282] Return "Function for JSDocType {Function} --- src/compiler/checker.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7b084a0f261..2d95f69f417 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2818,9 +2818,11 @@ namespace ts { const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); const modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(getSynthesizedClone); const dotDotDotToken = isRestParameter(parameterDeclaration) ? createToken(SyntaxKind.DotDotDotToken) : undefined; - const name = parameterDeclaration.name.kind === SyntaxKind.Identifier ? - setEmitFlags(getSynthesizedClone(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : - cloneBindingName(parameterDeclaration.name); + const name = parameterDeclaration.name ? + parameterDeclaration.name.kind === SyntaxKind.Identifier ? + setEmitFlags(getSynthesizedClone(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : + cloneBindingName(parameterDeclaration.name) : + parameterSymbol.name; const questionToken = isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : undefined; let parameterType = getTypeOfSymbol(parameterSymbol); @@ -6852,7 +6854,7 @@ namespace ts { case "Object": return anyType; case "Function": - return anyFunctionType; + return globalFunctionType; case "Array": case "array": return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined; From 72e6678804f2342e4ee4f1c25173d36b14f89ea4 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Tue, 23 May 2017 16:11:13 -0700 Subject: [PATCH 279/282] Update baselines --- ...jsFileCompilationRestParamJsDocFunction.types | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types b/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types index 66e3da3e67f..54bc7938689 100644 --- a/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types +++ b/tests/baselines/reference/jsFileCompilationRestParamJsDocFunction.types @@ -10,8 +10,8 @@ * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { ->apply : (func: {}, thisArg: any, ...args: any[]) => any ->func : {} +>apply : (func: Function, thisArg: any, ...args: any[]) => any +>func : Function >thisArg : any >args : any[] @@ -28,7 +28,7 @@ function apply(func, thisArg, args) { >0 : 0 >func.call(thisArg) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any @@ -36,7 +36,7 @@ function apply(func, thisArg, args) { >1 : 1 >func.call(thisArg, args[0]) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any >args[0] : any @@ -47,7 +47,7 @@ function apply(func, thisArg, args) { >2 : 2 >func.call(thisArg, args[0], args[1]) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any >args[0] : any @@ -61,7 +61,7 @@ function apply(func, thisArg, args) { >3 : 3 >func.call(thisArg, args[0], args[1], args[2]) : any >func.call : (this: Function, thisArg: any, ...argArray: any[]) => any ->func : {} +>func : Function >call : (this: Function, thisArg: any, ...argArray: any[]) => any >thisArg : any >args[0] : any @@ -77,12 +77,12 @@ function apply(func, thisArg, args) { return func.apply(thisArg, args); >func.apply(thisArg, args) : any >func.apply : (this: Function, thisArg: any, argArray?: any) => any ->func : {} +>func : Function >apply : (this: Function, thisArg: any, argArray?: any) => any >thisArg : any >args : any[] } export default apply; ->apply : (func: {}, thisArg: any, ...args: any[]) => any +>apply : (func: Function, thisArg: any, ...args: any[]) => any From bd422e3a524e1fb8c975e660e6a70cb8446a33a8 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Tue, 23 May 2017 16:11:23 -0700 Subject: [PATCH 280/282] Add tests and update baselines --- tests/baselines/reference/jsDocTypeTag1.js | 584 +++++++++++++++++ tests/baselines/reference/jsDocTypeTag2.js | 598 ++++++++++++++++++ tests/baselines/reference/jsDocTypes2.js | 37 ++ tests/baselines/reference/jsDocTypes2.symbols | 40 ++ tests/baselines/reference/jsDocTypes2.types | 59 ++ .../reference/jsDocTypes3.errors.txt | 21 + tests/baselines/reference/jsDocTypes3.js | 24 + tests/cases/conformance/salsa/jsDocTypes2.ts | 23 + tests/cases/conformance/salsa/jsDocTypes3.ts | 16 + .../cases/fourslash/jsDocTypeTagQuickInfo1.ts | 43 ++ .../cases/fourslash/jsDocTypeTagQuickInfo2.ts | 40 ++ 11 files changed, 1485 insertions(+) create mode 100644 tests/baselines/reference/jsDocTypeTag1.js create mode 100644 tests/baselines/reference/jsDocTypeTag2.js create mode 100644 tests/baselines/reference/jsDocTypes2.js create mode 100644 tests/baselines/reference/jsDocTypes2.symbols create mode 100644 tests/baselines/reference/jsDocTypes2.types create mode 100644 tests/baselines/reference/jsDocTypes3.errors.txt create mode 100644 tests/baselines/reference/jsDocTypes3.js create mode 100644 tests/cases/conformance/salsa/jsDocTypes2.ts create mode 100644 tests/cases/conformance/salsa/jsDocTypes3.ts create mode 100644 tests/cases/fourslash/jsDocTypeTagQuickInfo1.ts create mode 100644 tests/cases/fourslash/jsDocTypeTagQuickInfo2.ts diff --git a/tests/baselines/reference/jsDocTypeTag1.js b/tests/baselines/reference/jsDocTypeTag1.js new file mode 100644 index 00000000000..5dcabf2aa09 --- /dev/null +++ b/tests/baselines/reference/jsDocTypeTag1.js @@ -0,0 +1,584 @@ +[ + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 26 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 26, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "S", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 55 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 55, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "N", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 85 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 85, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "B", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "boolean", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 112 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 112, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "V", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "void", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 144 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 144, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "U", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "undefined", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 171 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 171, + "length": 2 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Nl", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "null", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 200 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 200, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "A", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": "[", + "kind": "punctuation" + }, + { + "text": "]", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 230 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 230, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "P", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Promise", + "kind": "interfaceName" + }, + { + "text": "<", + "kind": "punctuation" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": ">", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 259 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 259, + "length": 3 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Obj", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 292 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 292, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Func", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Function", + "kind": "localName" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 319 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 319, + "length": 7 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "AnyType", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 349 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 349, + "length": 5 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "QType", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag1.js", + "position": 389 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 389, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "SOrN", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "|", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + } +] \ No newline at end of file diff --git a/tests/baselines/reference/jsDocTypeTag2.js b/tests/baselines/reference/jsDocTypeTag2.js new file mode 100644 index 00000000000..07535dcee08 --- /dev/null +++ b/tests/baselines/reference/jsDocTypeTag2.js @@ -0,0 +1,598 @@ +[ + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 26 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 26, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "s", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 55 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 55, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "n", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 85 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 85, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "b", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "boolean", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 112 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 112, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "v", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "void", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 144 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 144, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "u", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "undefined", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 171 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 171, + "length": 2 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "nl", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "null", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 200 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 200, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "a", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": "[", + "kind": "punctuation" + }, + { + "text": "]", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 230 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 230, + "length": 1 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "p", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "Promise", + "kind": "interfaceName" + }, + { + "text": "<", + "kind": "punctuation" + }, + { + "text": "any", + "kind": "keyword" + }, + { + "text": ">", + "kind": "punctuation" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 260 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 260, + "length": 8 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "nullable", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 298 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 298, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "func", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "(", + "kind": "punctuation" + }, + { + "text": ")", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "=>", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "any", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 349 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 349, + "length": 5 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "func1", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "(", + "kind": "punctuation" + }, + { + "text": "arg0", + "kind": "parameterName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + }, + { + "text": ")", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "=>", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + }, + { + "marker": { + "fileName": "/tests/cases/fourslash/jsDocTypeTag2.js", + "position": 391 + }, + "quickInfo": { + "kind": "var", + "kindModifiers": "", + "textSpan": { + "start": 391, + "length": 4 + }, + "displayParts": [ + { + "text": "var", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "sOrn", + "kind": "localName" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "|", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "number", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [] + } + } +] \ No newline at end of file diff --git a/tests/baselines/reference/jsDocTypes2.js b/tests/baselines/reference/jsDocTypes2.js new file mode 100644 index 00000000000..a3848704fad --- /dev/null +++ b/tests/baselines/reference/jsDocTypes2.js @@ -0,0 +1,37 @@ +//// [0.js] +// @ts-check +/** @type {*} */ +var anyT = 2; + +/** @type {?} */ +var anyT1 = 2; +anyT1 = "hi"; + +/** @type {Function} */ +const x = (a) => a + 1; +x(1); + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1(0); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +x2(0); + +//// [0.js] +// @ts-check +/** @type {*} */ +var anyT = 2; +/** @type {?} */ +var anyT1 = 2; +anyT1 = "hi"; +/** @type {Function} */ +var x = function (a) { return a + 1; }; +x(1); +/** @type {function (number)} */ +var x1 = function (a) { return a + 1; }; +x1(0); +/** @type {function (number): number} */ +var x2 = function (a) { return a + 1; }; +x2(0); diff --git a/tests/baselines/reference/jsDocTypes2.symbols b/tests/baselines/reference/jsDocTypes2.symbols new file mode 100644 index 00000000000..96b32b9ad91 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes2.symbols @@ -0,0 +1,40 @@ +=== tests/cases/conformance/salsa/0.js === +// @ts-check +/** @type {*} */ +var anyT = 2; +>anyT : Symbol(anyT, Decl(0.js, 2, 3)) + +/** @type {?} */ +var anyT1 = 2; +>anyT1 : Symbol(anyT1, Decl(0.js, 5, 3)) + +anyT1 = "hi"; +>anyT1 : Symbol(anyT1, Decl(0.js, 5, 3)) + +/** @type {Function} */ +const x = (a) => a + 1; +>x : Symbol(x, Decl(0.js, 9, 5)) +>a : Symbol(a, Decl(0.js, 9, 11)) +>a : Symbol(a, Decl(0.js, 9, 11)) + +x(1); +>x : Symbol(x, Decl(0.js, 9, 5)) + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +>x1 : Symbol(x1, Decl(0.js, 13, 5)) +>a : Symbol(a, Decl(0.js, 13, 12)) +>a : Symbol(a, Decl(0.js, 13, 12)) + +x1(0); +>x1 : Symbol(x1, Decl(0.js, 13, 5)) + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +>x2 : Symbol(x2, Decl(0.js, 17, 5)) +>a : Symbol(a, Decl(0.js, 17, 12)) +>a : Symbol(a, Decl(0.js, 17, 12)) + +x2(0); +>x2 : Symbol(x2, Decl(0.js, 17, 5)) + diff --git a/tests/baselines/reference/jsDocTypes2.types b/tests/baselines/reference/jsDocTypes2.types new file mode 100644 index 00000000000..db5a5902d10 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes2.types @@ -0,0 +1,59 @@ +=== tests/cases/conformance/salsa/0.js === +// @ts-check +/** @type {*} */ +var anyT = 2; +>anyT : any +>2 : 2 + +/** @type {?} */ +var anyT1 = 2; +>anyT1 : any +>2 : 2 + +anyT1 = "hi"; +>anyT1 = "hi" : "hi" +>anyT1 : any +>"hi" : "hi" + +/** @type {Function} */ +const x = (a) => a + 1; +>x : Function +>(a) => a + 1 : (a: any) => any +>a : any +>a + 1 : any +>a : any +>1 : 1 + +x(1); +>x(1) : any +>x : Function +>1 : 1 + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +>x1 : (arg0: number) => any +>(a) => a + 1 : (a: any) => any +>a : any +>a + 1 : any +>a : any +>1 : 1 + +x1(0); +>x1(0) : any +>x1 : (arg0: number) => any +>0 : 0 + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +>x2 : (arg0: number) => number +>(a) => a + 1 : (a: any) => any +>a : any +>a + 1 : any +>a : any +>1 : 1 + +x2(0); +>x2(0) : number +>x2 : (arg0: number) => number +>0 : 0 + diff --git a/tests/baselines/reference/jsDocTypes3.errors.txt b/tests/baselines/reference/jsDocTypes3.errors.txt new file mode 100644 index 00000000000..5f5feeaf0a7 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes3.errors.txt @@ -0,0 +1,21 @@ +tests/cases/conformance/salsa/0.js(5,4): error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'. +tests/cases/conformance/salsa/0.js(12,1): error TS2322: Type 'number' is not assignable to type 'string'. + + +==== tests/cases/conformance/salsa/0.js (2 errors) ==== + // @ts-check + + /** @type {function (number)} */ + const x1 = (a) => a + 1; + x1("string"); + ~~~~~~~~ +!!! error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'. + + /** @type {function (number): number} */ + const x2 = (a) => a + 1; + + /** @type {string} */ + var a; + a = x2(0); + ~ +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/jsDocTypes3.js b/tests/baselines/reference/jsDocTypes3.js new file mode 100644 index 00000000000..2eb50223ba2 --- /dev/null +++ b/tests/baselines/reference/jsDocTypes3.js @@ -0,0 +1,24 @@ +//// [0.js] +// @ts-check + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1("string"); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; + +/** @type {string} */ +var a; +a = x2(0); + +//// [0.js] +// @ts-check +/** @type {function (number)} */ +var x1 = function (a) { return a + 1; }; +x1("string"); +/** @type {function (number): number} */ +var x2 = function (a) { return a + 1; }; +/** @type {string} */ +var a; +a = x2(0); diff --git a/tests/cases/conformance/salsa/jsDocTypes2.ts b/tests/cases/conformance/salsa/jsDocTypes2.ts new file mode 100644 index 00000000000..612804b91d7 --- /dev/null +++ b/tests/cases/conformance/salsa/jsDocTypes2.ts @@ -0,0 +1,23 @@ +// @allowJS: true +// @suppressOutputPathCheck: true + +// @filename: 0.js +// @ts-check +/** @type {*} */ +var anyT = 2; + +/** @type {?} */ +var anyT1 = 2; +anyT1 = "hi"; + +/** @type {Function} */ +const x = (a) => a + 1; +x(1); + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1(0); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; +x2(0); \ No newline at end of file diff --git a/tests/cases/conformance/salsa/jsDocTypes3.ts b/tests/cases/conformance/salsa/jsDocTypes3.ts new file mode 100644 index 00000000000..bf207bca869 --- /dev/null +++ b/tests/cases/conformance/salsa/jsDocTypes3.ts @@ -0,0 +1,16 @@ +// @allowJS: true +// @suppressOutputPathCheck: true + +// @filename: 0.js +// @ts-check + +/** @type {function (number)} */ +const x1 = (a) => a + 1; +x1("string"); + +/** @type {function (number): number} */ +const x2 = (a) => a + 1; + +/** @type {string} */ +var a; +a = x2(0); \ No newline at end of file diff --git a/tests/cases/fourslash/jsDocTypeTagQuickInfo1.ts b/tests/cases/fourslash/jsDocTypeTagQuickInfo1.ts new file mode 100644 index 00000000000..240c00e2283 --- /dev/null +++ b/tests/cases/fourslash/jsDocTypeTagQuickInfo1.ts @@ -0,0 +1,43 @@ +/// +// @allowJs: true +// @Filename: jsDocTypeTag1.js +//// /** @type {String} */ +//// var /*1*/S; + +//// /** @type {Number} */ +//// var /*2*/N; + +//// /** @type {Boolean} */ +//// var /*3*/B; + +//// /** @type {Void} */ +//// var /*4*/V; + +//// /** @type {Undefined} */ +//// var /*5*/U; + +//// /** @type {Null} */ +//// var /*6*/Nl; + +//// /** @type {Array} */ +//// var /*7*/A; + +//// /** @type {Promise} */ +//// var /*8*/P; + +//// /** @type {Object} */ +//// var /*9*/Obj; + +//// /** @type {Function} */ +//// var /*10*/Func; + +//// /** @type {*} */ +//// var /*11*/AnyType; + +//// /** @type {?} */ +//// var /*12*/QType; + +//// /** @type {String|Number} */ +//// var /*13*/SOrN; + +verify.baselineQuickInfo(); \ No newline at end of file diff --git a/tests/cases/fourslash/jsDocTypeTagQuickInfo2.ts b/tests/cases/fourslash/jsDocTypeTagQuickInfo2.ts new file mode 100644 index 00000000000..7c79116b041 --- /dev/null +++ b/tests/cases/fourslash/jsDocTypeTagQuickInfo2.ts @@ -0,0 +1,40 @@ +/// +// @allowJs: true +// @Filename: jsDocTypeTag2.js +//// /** @type {string} */ +//// var /*1*/s; + +//// /** @type {number} */ +//// var /*2*/n; + +//// /** @type {boolean} */ +//// var /*3*/b; + +//// /** @type {void} */ +//// var /*4*/v; + +//// /** @type {undefined} */ +//// var /*5*/u; + +//// /** @type {null} */ +//// var /*6*/nl; + +//// /** @type {array} */ +//// var /*7*/a; + +//// /** @type {promise} */ +//// var /*8*/p; + +//// /** @type {?number} */ +//// var /*9*/nullable; + +//// /** @type {function} */ +//// var /*10*/func; + +//// /** @type {function (number): number} */ +//// var /*11*/func1; + +//// /** @type {string | number} */ +//// var /*12*/sOrn; + +verify.baselineQuickInfo(); \ No newline at end of file From 34bb955655554a5b8818b1f97696ef0881bdf7ea Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 24 May 2017 08:42:02 -0700 Subject: [PATCH 281/282] Use `orderedRemoveItem` instead of `remove` helper --- src/server/project.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/server/project.ts b/src/server/project.ts index 6372d1f5c03..7dc4388bf39 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -13,13 +13,6 @@ namespace ts.server { External } - function remove(items: T[], item: T) { - const index = items.indexOf(item); - if (index >= 0) { - items.splice(index, 1); - } - } - function countEachFileTypes(infos: ScriptInfo[]): { js: number, jsx: number, ts: number, tsx: number, dts: number } { const result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; for (const info of infos) { @@ -732,7 +725,7 @@ namespace ts.server { // remove a root file from project protected removeRoot(info: ScriptInfo): void { - remove(this.rootFiles, info); + orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.remove(info.path); } } From f309996b329702da7ad2725dade35c4b950f4a47 Mon Sep 17 00:00:00 2001 From: Donald Pipowitch Date: Wed, 24 May 2017 18:50:38 +0200 Subject: [PATCH 282/282] added es2017.intl (#15369) --- Gulpfile.ts | 1 + Jakefile.js | 3 ++- lib/lib.es2017.d.ts | 3 ++- lib/lib.es2017.full.d.ts | 1 + lib/tsc.js | 1 + lib/tsserver.js | 1 + lib/tsserverlibrary.js | 1 + lib/typescript.js | 1 + lib/typescriptServices.js | 1 + lib/typingsInstaller.js | 1 + src/compiler/commandLineParser.ts | 3 ++- src/harness/unittests/commandLineParsing.ts | 6 +++--- .../unittests/convertCompilerOptionsFromJson.ts | 8 ++++---- src/lib/es2017.d.ts | 3 ++- src/lib/es2017.intl.d.ts | 10 ++++++++++ 15 files changed, 33 insertions(+), 11 deletions(-) create mode 100644 src/lib/es2017.intl.d.ts diff --git a/Gulpfile.ts b/Gulpfile.ts index 03046789fe1..d856254296e 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -131,6 +131,7 @@ const es2017LibrarySource = [ "es2017.object.d.ts", "es2017.sharedmemory.d.ts", "es2017.string.d.ts", + "es2017.intl.d.ts", ]; const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) { diff --git a/Jakefile.js b/Jakefile.js index 807546d59f8..577ade2ef69 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -172,7 +172,8 @@ var es2016LibrarySourceMap = es2016LibrarySource.map(function (source) { var es2017LibrarySource = [ "es2017.object.d.ts", "es2017.sharedmemory.d.ts", - "es2017.string.d.ts" + "es2017.string.d.ts", + "es2017.intl.d.ts" ]; var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) { diff --git a/lib/lib.es2017.d.ts b/lib/lib.es2017.d.ts index a0d3a0aff28..64ebe606847 100644 --- a/lib/lib.es2017.d.ts +++ b/lib/lib.es2017.d.ts @@ -21,4 +21,5 @@ and limitations under the License. /// /// /// -/// \ No newline at end of file +/// +/// \ No newline at end of file diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index d70049b1309..91bee6e9d56 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -22,6 +22,7 @@ and limitations under the License. /// /// /// +/// declare type PropertyKey = string | number | symbol; diff --git a/lib/tsc.js b/lib/tsc.js index 1d92d339b9d..4c846c034f8 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -56880,6 +56880,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, diff --git a/lib/tsserver.js b/lib/tsserver.js index ae6c3c8dc07..0e99abde9da 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -56898,6 +56898,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index e23edda9295..128438ce66a 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -6079,6 +6079,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, diff --git a/lib/typescript.js b/lib/typescript.js index a73895f4f74..9f28644b4e5 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -69276,6 +69276,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index a73895f4f74..9f28644b4e5 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -69276,6 +69276,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 4efda1e469e..554dc3bcaca 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -6071,6 +6071,7 @@ var ts; "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 9494098c072..88687357115 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -139,6 +139,7 @@ namespace ts { "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", + "es2017.intl": "lib.es2017.intl.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -1704,4 +1705,4 @@ namespace ts { function caseInsensitiveKeyMapper(key: string) { return key.toLowerCase(); } -} \ No newline at end of file +} diff --git a/src/harness/unittests/commandLineParsing.ts b/src/harness/unittests/commandLineParsing.ts index 61b96d89553..19ccc919d4c 100644 --- a/src/harness/unittests/commandLineParsing.ts +++ b/src/harness/unittests/commandLineParsing.ts @@ -60,7 +60,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -263,7 +263,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -283,7 +283,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, diff --git a/src/harness/unittests/convertCompilerOptionsFromJson.ts b/src/harness/unittests/convertCompilerOptionsFromJson.ts index 0409ee19e66..3aa1a4c9b8e 100644 --- a/src/harness/unittests/convertCompilerOptionsFromJson.ts +++ b/src/harness/unittests/convertCompilerOptionsFromJson.ts @@ -233,7 +233,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -264,7 +264,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -295,7 +295,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -326,7 +326,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] diff --git a/src/lib/es2017.d.ts b/src/lib/es2017.d.ts index 7b8c7cbb7d5..80282355a45 100644 --- a/src/lib/es2017.d.ts +++ b/src/lib/es2017.d.ts @@ -1,4 +1,5 @@ /// /// /// -/// \ No newline at end of file +/// +/// diff --git a/src/lib/es2017.intl.d.ts b/src/lib/es2017.intl.d.ts new file mode 100644 index 00000000000..b8783530190 --- /dev/null +++ b/src/lib/es2017.intl.d.ts @@ -0,0 +1,10 @@ +type DateTimeFormatPartTypes = "day" | "dayPeriod" | "era" | "hour" | "literal" | "minute" | "month" | "second" | "timeZoneName" | "weekday" | "year"; + +interface DateTimeFormatPart { + type: DateTimeFormatPartTypes; + value: string; +} + +interface DateTimeFormat { + formatToParts(date?: Date | number): DateTimeFormatPart[]; +}